实现用户信息的增删改-mongoose数据库操作

const http = require('http');
const server = http.createServer();
const mongoose = require('mongoose');
const url = require('url')
const mime = require('mime')
const querystring = require('querystring')
mongoose.connect('mongodb://localhost/play', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(result => console.log('连接成功'))
    .catch(err => console.log(err, '连接失败'))

// 创建用户集合
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20
    },
    age: {
        type: Number,
        min: 18,
        max: 80
    },
    password: String,
    email: String,
    hobbies: [String]
})
const User = mongoose.model('User', userSchema)
server.listen(8000)
server.on('request', async(req, res) => {
    const method = req.method;
    const { pathname, query } = url.parse(req.url, true)
    let type = mime.getType(pathname)
    let hobby = ['足球', '篮球', '橄榄球 ', '敲代码 ', '抽烟', '喝酒 ', '烫头']
    if (method == 'GET') {
        if (pathname == '/list') {
            // 查询用户信息,为了让能用户信息先拿到,再执行后面的代码,需要用异步函数。
            let users = await User.find()
            let list = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>用户列表</title>
                <link rel="stylesheet" href="css/bootstrap.min.css">
                <!-- <script src="js/bootstrap.min.js"></script> -->
              
            </head>
            
            <body>
                <div class="container">
                    <a href="/add" class="btn btn-primary margin-top" type="button">
                  添加用户
                </a>
                    <form action="localhost:8090">
                        <table>
                            <tr>
                                <th>用户名</th>
                                <th>年龄</th>
                                <th>爱好</th>
                                <th>邮箱</th>
                                <th>操作</th>
                            </tr>
                `;
            // 对数据进行循环操作
            users.forEach((item) => {
                list += `<tr>
                    <td>${item.name}</td>
                    <td>${item.age}</td>
                    <td>`
                item.hobbies.forEach(item => {
                    list += `<span>${item}</span>`
                })
                list += `
                    </td>
                    <td>${item.email}</td>
                    <td><a href="delete?id=${item._id}" >删除</a><a href="modify?id=${item._id}" >修改</a></td>
                </tr>`
            })
            list += `   </table>
                    </form>
                </div>
                <script>
                    var button = document.querySelector('button')
            
                    button.onclick = function() {
                        console.log(11)
                    }
                </script>
            </body>
            </html>`
            res.end(list)
        } else if (pathname == '/add') {
            let add = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>添加用户t</title>
                <link rel="stylesheet" href="css/bootstrap.min.css">
                <style>
                    label {
                        margin-top: 10px;
                        display: block;
                        font-size: 16px;
                    }
                    
                    input {
                        outline: none;
                    }
                    
                    button {
                        display: block !important;
                        margin-top: 10px;
                    }
                </style>
            </head>
            <div class="container">
                <h3>添加用户</h3>
                <form method="post" action="/add" >
                
                    <label for="username">用户名</label>
                    <input type="text" value='请填写用户名' name='name'>
                    <label for="password">密码</label>
                    <input type="password" value='请输入密码' name='password'>
                    <label for="age">年龄</label>
                    <input type="text" value='请填写年龄' name='age'>
                    <label for="email">邮箱</label>
                    <input type="text" value='请填写邮箱' name='email'>
                    <label>请选择爱好</label>
                    <input type="checkbox" name="hobbies" value="足球">足球
                    <input type="checkbox" name="hobbies" value="篮球">篮球
                    <input type="checkbox" name="hobbies" value="橄榄球">橄榄球
                    <input type="checkbox" name="hobbies" value="敲代码">敲代码
                    <input type="checkbox" name="hobbies" value="抽烟">抽烟
                    <input type="checkbox" name="hobbies" value="喝酒">喝酒
                    <input type="checkbox" name="hobbies" value="烫头">烫头
                    <input type="submit" class="btn btn-primary margin-top" value="添加用户">
                </form>
                <script>
                    var checkboxs = document.querySelectorAll('input')
                    for (var i = 0; i < checkboxs.length; i++) {
                        if (checkboxs[i].type != 'checkbox') {
                            checkboxs[i].style.width = '100%';
                        }
            
                    }
                </script>
            </div>
            
            <body>
            
            </body>
            
            </html>`
            res.end(add)
        } else if (pathname == '/modify') {
            let user = await User.findOne({ _id: query.id })
            let modify = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>修改用户t</title>
                <link rel="stylesheet" href="css/bootstrap.min.css">
              
            </head>
            <div class="container">
                <h3>修改用户</h3>
                <form method="post" action="/modify?id=${user._id}" >
                    <label for="username">用户名</label>
                    <input type="text" value='${user.name}' name='name'>
                    <label for="password">密码</label>
                    <input type="password" value='${user.password}' name='password'>
                    <label for="age">年龄</label>
                    <input type="text" value='${user.age}' name='age'>
                    <label for="email">邮箱</label>
                    <input type="text" value='${user.email}' name='email'>
                    <label>请选择爱好</label>`
            hobby.forEach(item => {
                console.log(user.hobbies)
                let ishobby = user.hobbies.includes(item)

                if (ishobby) {
                    modify += `<input type = "checkbox"  name = "hobbies" value = "${item}" checked=checked > ${item} `
                } else {
                    modify += `<input type = "checkbox"  name = "hobbies" value = "${item}"> ${item} `
                }
            })
            modify += `    
            <div>  
            <input type="submit" class="btn btn-primary margin-top" value="修改用户">
            </div>
            </form>
            <script>
                var checkboxs = document.querySelectorAll('input')
                for (var i = 0; i < checkboxs.length; i++) {
                    if (checkboxs[i].type != 'checkbox') {
                        checkboxs[i].style.width = '100%';
                    }
                }
            </script>
        </div>
        
        <body>
        </body>
        </html>`
            res.end(modify)

        } else if (pathname == '/delete') {
            console.log(query.id)
            await User.findOneAndDelete({ _id: query.id })
            res.writeHead(301, {
                Location: '/list'
            })
            res.end()
        }
    } else if (method == 'POST') {
        if (pathname == '/add') {
            let formDatas = ''
            req.on('data', (param) => {
                formDatas = formDatas + param
            })
            req.on('end', async() => {
                let user = querystring.parse(formDatas)
                console.log(user)
                await User.create(user)
                    // 301代表重定向
                res.writeHead(301, {
                    Location: '/list'
                })
                res.end()
            })
        } else if (pathname == '/modify') {
            let formDatas = ''
            req.on('data', (param) => {
                formDatas = formDatas + param
            })

            req.on('end', async() => {
                let user = querystring.parse(formDatas)
                await User.updateOne({ _id: query.id }, user)
                    // 301代表重定向
                res.writeHead(301, {
                    Location: '/list'
                })
                res.end()
            })
        }

    }
    res.writeHead(200, { 'Content-Type': type })
})

  

原文地址:https://www.cnblogs.com/rainbowupdate/p/12692369.html