用nodejs构建MongoDB数据库,实现用户管理系统 | 小项目

最终效果如图:通过修改表单,可以对数据库的内容增添改删。
在这里插入图片描述

代码1:list.html 主页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户列表</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            text-align: center;
        }
        a{
            text-decoration: none;
            color:white;
        }
        h6{
            
            width: 80px;
            background-color: #2b71b8;
            line-height: 30px;
            border-radius: 3px;
            margin-bottom: 20px;
        }
        body{
            display: flex;
            height: 100vh;
            justify-content: center;
            margin-top: 50px;
        }
        th,td{
            border:1px solid #999;
            padding: 10px 15px;
        }
        th{
            background-color: #f0f3f0;
        }
        table{
            border-collapse: collapse;
        }
        td a{
            margin-right: 2px;
            display: inline-block;
            width: 43px;
            height: 30px;
            line-height: 30px;
            border-radius: 4px;
        }
        td a:nth-of-type(1){
            background-color: #e35d4a;
        }
        td a:nth-of-type(2){
            background-color: #55a95a;
        }
    </style>
</head>
<body>
    <div class="container">
        <h6>
            <a href="add">添加用户</a>
        </h6>
        <table>
            <tr>
                <th>用户名</th>
                <th>年龄</th>
                <th>爱好</th>
                <th>邮箱</th>
                <th>操作</th>
            </tr>
            <tr>
                <td>张三</td>
                <td>20</td>
                <td>
                    <span>编程</span>
                    <span>唱歌</span>
                    <span>运动</span>
                </td>
                <td>zhangsan@qq.com</td>
                <td>
                    <a href="" id="del">删除</a>
                    <a href=""  id="modify">修改</a>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

html 效果:
在这里插入图片描述

代码2: add.html 添加数据页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加用户</title>
    <style>
        .container{
            width: 80vw;
            margin: 20px auto;
        }
        h3{
            font-size: 29px;
            font-weight: normal;
            margin: 0;
            margin-bottom: 20px;
        }
        .form-group input{
            width: 80vw;
            
            height: 20px;
        }
        label.label{
            display: block;
            font-weight:600;
            margin: 10px 0;
        }
        button{
            margin: 20px 0;
            background-color: #2f80bc;
            color:white;
            font-size: 17px;
            padding: 4px 8px;
            border:0;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h3>添加用户</h3>
        <form method="post" action="/add">
            <div class="form-group">
                <label class="label">用户名</label>
                <input type="text" id='name' name="name" class="form-control" placeholder="请填写用户名">
            </div>
            <div class="form-group">
                <label class="label">密码</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label class="label">年龄</label>
                <input type="number"name="age" id="age" class="form-control" placeholder="请填写年龄" max="120" min="0">
            </div>
            <div class="form-group">
                <label class="label">邮箱</label>
                <input type="email" name="email" class="form-control" placeholder="请输入邮箱" id="email">
            </div>
            <div>
                <label class="label">请选择爱好</label>
            </div>
            <div id="checkbox-container">
                <input type="checkbox" name="hobbies" id="bask" value="篮球"> <label for="bask">篮球</label>
                <input type="checkbox" name="hobbies" id="code" value="coding"> <label for="code">coding</label>
                <input type="checkbox" name="hobbies" id="ping" value="乒乓"> <label for="ping">乒乓球</label>
                <input type="checkbox" name="hobbies" id="sing" value="唱歌"> <label for="sing">唱歌</label>
                <input type="checkbox" name="hobbies" id="draw" value="画画"> <label for="draw">画画</label>
            </div>
            <button>添加用户</button>
        </form>
    </div>
</body>
</html>

在这里插入图片描述

代码3:index.js 项目主体

要实现下面的代码,需要安装 node.jsmongoDB,并在终端中输入net start mongoDB开启数据库。

而且还有安装第3方模块,nodeMon:自动更新服务器;mongoose: 在nodejs中方便的操控MongoDB数据库;cheerio,在nodejs中用jquery的方式操控dom。

// 1.引入模块
const mongoose = require('mongoose');
const http = require('http');
const fs = require('fs');
const queryString = require('querystring');
const Url = require('url');
const cheerio = require('cheerio');

// 2.连接数据库
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => { console.log('数据库连接成功') })
    .catch(err => { console.log(err) });

// 3.创建集合规则
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        minlength: 2,
        maxlength: 20,
        required: true
    },
    age: {
        type: Number,
        max: 120,
        min: 0
    },
    password: String,
    email: String,
    hobbies: [String]
})

// 4.使用规则创建集合
const User = mongoose.model('User', UserSchema)

let listHTML, addHTML;
// 5.读取html页面上的数据
fs.readFile('list.html', 'utf-8', (err, result) => {
    if (err) return console.log(err);
    listHTML = result;
});
fs.readFile('add.html', 'utf-8', (err, result) => {
    if (err) return console.log(err);
    addHTML = result;
})

// 6.使用node的http模块创建服务器
// 用到了async和await,这样就可以先加载出所有数据再加载HTML
http.createServer(async (req, res) => {
    const method = req.method;
    const url = req.url;
    // 8.2使用url模块来获取,true代表返回的query为对象类型
    const query = Url.parse(url, true).query;
    if (method == 'GET') {
        if (url == '/') {
            // 从数据库中查询信息
            let users = await User.find();
            // 拼接HTML
            // 6.1拼接HTML的头部
            let list = /<![\s\S]*<\/h6>/.exec(listHTML);
            list += ` <table>
            <tr>
                <th>用户名</th>
                <th>年龄</th>
                <th>爱好</th>
                <th>邮箱</th>
                <th>操作</th>
            </tr>`
            // 6.2拼接来的数据库中的数据
            users.forEach(item => {
                list += `<tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>`
                item.hobbies.forEach((hobby) => {
                    list += `<span>${hobby} </span>`
                })
                list += `</td>
                <td>${item.email}</td>
                <td>
                    <a href="/remove?id=${item._id}" id="del">删除</a>
                    <a href="/modify?id=${item._id}"  id="modify">修改</a>
                </td>
            </tr>`
            });

            // 6.3 拼接HTML的尾部
            list += /<\/table>[\s\S]*<\/html>/.exec(listHTML);
            res.end(list);

        }
        // 7.1当用户点击主页面的添加按钮时响应添加按钮的页面
        else if (url == '/add') {
            res.end(addHTML)
        }
        // 8.1修改用户信息
        else if (url.includes('/modify')) {
            // 8.2 获取url路径中的id

            // 8.3 根据id查找用户信息
            let user = await User.findOne({ _id: query.id });
            // 8.3 准备好返回的html内容
            const reg = new RegExp('添加用户', 'g')
            const modifyHTML = addHTML.replace(reg, '修改用户').replace('/add', `/modify?id=${user._id}`)
            // 8.4 使用第三方库cheerio,用服务器中的数据修改modifyHTML
            $ = cheerio.load(modifyHTML);
            $('#name').val(user.name);
            $('#age').val(user.age);
            $('#email').val(user.email);
            $('#password').val(user.password);
            $('#checkbox-container')[0];
            $(':checkbox').each(function () {
                if (user.hobbies.includes($(this).val())) {
                    $(this).prop('checked', 'check')
                }
            });
            // 8.5将修改好的值返回给客户端
            res.end($.html());
        }
        // 9 删除用户信息
        else if(url.includes('/remove')){
            await User.findOneAndDelete({_id:query.id});
            res.writeHead(301,{location:'/'});
            res.end();
        }
    }
    else if (method == 'POST') {
        // 7.2在add页面,用户点击提交表单时
        if (url == '/add') {
            // 7.3接受用户提交的信息
            let formData = '';
            // 接受用户通过表单post的参数
            req.on('data', (param) => {
                formData += param;
            })

            req.on('end', async () => {
                let user = queryString.parse(formData);
                // 7.4将用户信息提交到数据库中
                await User.create(user);
                // 301代表重定向,重定向到首页
                res.writeHead(301, {
                    location: '/'
                });
                res.end();
            })
        }
        // 8.6 处理用户的修改提交
        if (url.includes('/modify')) {
            let formData = '';
            req.on('data', (param) => {
                formData += param;
            });
            req.on('end', async () => {
                let user = queryString.parse(formData);
                await User.updateOne({ _id: query.id },user);
                res.writeHead(301,{location:'/'});
                res.end();
            })
        }

    }
}).listen('3000', () => {
    console.log('running at http://localhost:3000');
});

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用 Node.js 和 MongoDB 构建进销存系统的数据表可以让你轻松地处理数据操作和管理。下面是一个基本的示例,展示如何使用 Node.js 和 MongoDB 创建、查询和更新进销存系统的数据表。 首先,确保你已经安装了 Node.js 和 MongoDB,并在项目文件夹中初始化了 Node.js 项目。 1. 连接到 MongoDB 数据库: ```javascript const mongoose = require('mongoose'); // 连接到 MongoDB 数据库 mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true, }); // 创建数据库连接 const db = mongoose.connection; // 监听连接是否成功 db.on('error', console.error.bind(console, '连接错误:')); db.once('open', function () { console.log('成功连接到数据库!'); }); ``` 2. 创建产品模型: ```javascript const mongoose = require('mongoose'); // 创建产品模型 const productSchema = new mongoose.Schema({ name: String, price: Number, quantity: Number, category: String, supplier: String, }); const Product = mongoose.model('Product', productSchema); ``` 3. 创建销售记录模型: ```javascript const mongoose = require('mongoose'); // 创建销售记录模型 const saleSchema = new mongoose.Schema({ product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, sale_date: Date, quantity: Number, amount: Number, customer: String, }); const Sale = mongoose.model('Sale', saleSchema); ``` 4. 创建进货记录模型: ```javascript const mongoose = require('mongoose'); // 创建进货记录模型 const purchaseSchema = new mongoose.Schema({ product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, purchase_date: Date, quantity: Number, cost: Number, supplier: String, }); const Purchase = mongoose.model('Purchase', purchaseSchema); ``` 5. 插入数据到产品表: ```javascript const product = new Product({ name: 'Product 1', price: 10, quantity: 100, category: 'Category 1', supplier: 'Supplier 1', }); product.save(function (err, savedProduct) { if (err) { console.error(err); } else { console.log('产品已保存:', savedProduct); } }); ``` 6. 查询产品列表: ```javascript Product.find({}, function (err, products) { if (err) { console.error(err); } else { console.log('产品列表:', products); } }); ``` 7. 更新产品信息: ```javascript Product.updateOne( { _id: 'product_id' }, { price: 15 }, function (err, result) { if (err) { console.error(err); } else { console.log('产品已更新:', result); } } ); ``` 这只是一个简单的示例,你可以根据你的具体需求和数据模型设计更复杂的数据表和操作。使用 Node.js 和 MongoDB,你可以轻松地创建和管理进销存系统的数据表,并进行各种数据操作和查询。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值