Node开发--->12_Node.js_mongoDB集合关联

2.7集合关联

文章集合中会包含与文章相关的字段,其中author字段是发表文章的作者,作者就是网站当中的注册用户,而用户信息是存储在另外一个集合中的
问:如何在文章集合中存储发表文章的用户信息呢?
答:实际上,不需要将作者的全部信息拷贝到文章集合中,只需要通过字段_id,将文章集合与用户集合进行关联就可以了。比如在author字段中将用户的_id存入即可。

问:如何获取author中具体的信息呢?比如name,age等
答:使用populate方法进行关联集合查询

1 创建用户集合与文章集合

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

//用户集合
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }
});


//文章集合
const postScheam = new mongoose.Schema({
    title: {
        type: String
    },
    author: {
        //author 字段将要存储的是一个_id,_id的数据类型就是mongoose.Schema.Types.ObjectId
        type: mongoose.Schema.Types.ObjectId,
        //将author字段与User集合进行关联
        ref: 'User'
    }
});

//创建用户
const User = mongoose.model('User', userSchema);
//创建文章
const Post = mongoose.model('Post', postScheam);

//创建用户
User.create({ name: 'ithema' }).then(res => console.log(res));
//创建文章
Post.create({ title: '123', author: '5e87e0a1a20a1659a07fe33d' }).then(res => console.log(res));

运行后

  • 文章集合

  • 用户集合

2 查询文章信息

(1)查询文章信息
在上述代码后追加

//查询文章信息
Post.find().then(res => console.log(res));

运行后

(2)查询文章中关联字段的信息

//查询文章信息
// Post.find().then(res => console.log(res));
//查询文章中author字段的信息
Post.find().populate('author').then(res => console.log(res));

2.8 案例:用户信息增删改查


(1)新建文件夹user,在user下新建文件夹app.js
(2)创建服务器,连接数据库,创建用户集合

const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', (req, res) => {
    res.end('ok');
})

//监听端口
app.listen(3000);

(3)将database文件夹下的user.json中的数据导入到刚才创建的users集合当中

打开campass也可以查看

(4)当用户访问/list的时候,将所有用户信息查询出来

  • 实现路由功能(获取用户的请求方式和地址,并对方式和地址进行判断)
  • 呈现用户列表页面
  • 从数据库中查询用户信息,并将用户信息显示在列表中
const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose
const url = require('url');

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', async(req, res) => {
    //请求方式
    const method = req.method;
    //请求地址
    const { pathname } = url.parse(req.url);
    if (method == 'GET') {
        //呈现用户列表页面
        if (pathname == '/list') {
            //查询用户信息
            let users = await User.find();
            // console.log(users);是一个数组,数组中的元素是对象,每个对象中包含着每个用户的信息

            //将静态代码与查询到的数据进行拼接
            let list = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="add.html" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>
            `;

            //对查询到的users数据进行循环操作,准备数据的拼接
            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="" class="btn btn-danger btn-xs">删除</a>
                    <a href="" class="btn btn-success btn-xs">修改</a>
                </td>
            </tr>`;
            });

            list += `
            </table>
                    </div>
                </body>
                </html>
            `;
            //将list变量响应给客户端
            res.end(list);
        }

    } else if (method == 'POST') {

    }

})

//监听端口
app.listen(3000);

刷新浏览器

(5)添加用户功能

const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose
const url = require('url');
const querystring = require('querystring');

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', async(req, res) => {
    //请求方式
    const method = req.method;
    //请求地址
    const { pathname } = url.parse(req.url);
    if (method == 'GET') {
        //呈现用户列表页面
        if (pathname == '/list') {
            //查询用户信息
            let users = await User.find();
            // console.log(users);是一个数组,数组中的元素是对象,每个对象中包含着每个用户的信息

            //将静态代码与查询到的数据进行拼接
            let list = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="/add" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>
            `;

            //对查询到的users数据进行循环操作,准备数据的拼接
            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="" class="btn btn-danger btn-xs">删除</a>
                    <a href="" class="btn btn-success btn-xs">修改</a>
                </td>
            </tr>`;
            });

            list += `
            </table>
                    </div>
                </body>
                </html>
            `;
            //将list变量响应给客户端
            res.end(list);
        } else if (pathname == '/add') {
            let add = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>添加用户</h3>
                    <form method='post' active="/add">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="足球" name="hobbies"> 足球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="篮球" name="hobbies"> 篮球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="烫头" name="hobbies"> 烫头
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">添加用户</button>
                    </form>
                </div>
            </body>
            </html>
                    `;
            res.end(add);
        }

    } else if (method == 'POST') {
        //添加用户功能
        if (pathname == '/add') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.create(user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });

        }
    }

})

//监听端口
app.listen(3000);

运行后用户添加成功后会跳转到列表页面

(6)修改用户信息功能
增加页面路由,呈现页面

  • 点击修改按钮的时候将用户的ID传递过来
  • 从数据库中查询当前用户信息,将用户信息展示到页面中
const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose
const url = require('url');
const querystring = require('querystring');

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', async(req, res) => {
    //请求方式
    const method = req.method;
    //请求地址
    const { pathname, query } = url.parse(req.url, true);
    if (method == 'GET') {
        //呈现用户列表页面
        if (pathname == '/list') {
            //查询用户信息
            let users = await User.find();
            // console.log(users);是一个数组,数组中的元素是对象,每个对象中包含着每个用户的信息

            //将静态代码与查询到的数据进行拼接
            let list = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="/add" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>
            `;

            //对查询到的users数据进行循环操作,准备数据的拼接
            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="" class="btn btn-danger btn-xs">删除</a>
                    <a href="\modify?id=${item.id}" class="btn btn-success btn-xs">修改</a>
                </td>
            </tr>`;
            });

            list += `
            </table>
                    </div>
                </body>
                </html>
            `;
            //将list变量响应给客户端
            res.end(list);
        } else if (pathname == '/add') {
            let add = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>添加用户</h3>
                    <form method='post' active="/add">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="足球" name="hobbies"> 足球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="篮球" name="hobbies"> 篮球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="烫头" name="hobbies"> 烫头
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">添加用户</button>
                    </form>
                </div>
            </body>
            </html>
                    `;
            res.end(add);
        } else if (pathname == '/modify') {
            let user = await User.findOne({ _id: query.id }); //返回一个对象,下面将对象中的参数与html文件进行拼接
            let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头'];
            console.log(user);

            let modify = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>修改用户</h3>
                    <form method='post' active="/add">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name" value="${user.name}">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password" value="${user.password}">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age" value="${user.age}">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email" value="${user.email}">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                        
                    `;

            hobbies.forEach(item => {
                //判断当前循环项是否在用户数组里
                let isHobby = user.hobbies.includes(item);
                if (isHobby) {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies" checked> ${item}
                    </label>
                    `;
                } else {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies"> ${item}
                    </label>
                    `;
                }
            });
            modify += `
            </div>
                    </div>
                    <button type="submit" class="btn btn-primary">修改用户</button>
                    </form>
                </div>
            </body>
            </html>
            `;
            res.end(modify);
        }

    } else if (method == 'POST') {
        //添加用户功能
        if (pathname == '/add') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.create(user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });

        }
    }

})

//监听端口
app.listen(3000);

实现用户修改功能

  • 指定表单的提交地址与请求方式
  • 在服务器端接收用户提交的修改信息,找到用户,将最新的修改信息更新到数据库中
const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose
const url = require('url');
const querystring = require('querystring');

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', async(req, res) => {
    //请求方式
    const method = req.method;
    //请求地址
    const { pathname, query } = url.parse(req.url, true);
    if (method == 'GET') {
        //呈现用户列表页面
        if (pathname == '/list') {
            //查询用户信息
            let users = await User.find();
            // console.log(users);是一个数组,数组中的元素是对象,每个对象中包含着每个用户的信息

            //将静态代码与查询到的数据进行拼接
            let list = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="/add" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>
            `;

            //对查询到的users数据进行循环操作,准备数据的拼接
            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="" class="btn btn-danger btn-xs">删除</a>
                    <a href="\modify?id=${item.id}" class="btn btn-success btn-xs">修改</a>
                </td>
            </tr>`;
            });

            list += `
            </table>
                    </div>
                </body>
                </html>
            `;
            //将list变量响应给客户端
            res.end(list);
        } else if (pathname == '/add') {
            let add = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>添加用户</h3>
                    <form method='post' active="/add">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="足球" name="hobbies"> 足球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="篮球" name="hobbies"> 篮球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="烫头" name="hobbies"> 烫头
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">添加用户</button>
                    </form>
                </div>
            </body>
            </html>
                    `;
            res.end(add);
        } else if (pathname == '/modify') {
            let user = await User.findOne({ _id: query.id }); //返回一个对象,下面将对象中的参数与html文件进行拼接
            let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头'];
            console.log(user);

            let modify = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>修改用户</h3>
                    <form method='post' active="/modify?id=${user._id}">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name" value="${user.name}">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password" value="${user.password}">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age" value="${user.age}">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email" value="${user.email}">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                        
                    `;

            hobbies.forEach(item => {
                //判断当前循环项是否在用户数组里
                let isHobby = user.hobbies.includes(item);
                if (isHobby) {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies" checked> ${item}
                    </label>
                    `;
                } else {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies"> ${item}
                    </label>
                    `;
                }
            });
            modify += `
            </div>
                    </div>
                    <button type="submit" class="btn btn-primary">修改用户</button>
                    </form>
                </div>
            </body>
            </html>
            `;
            res.end(modify);
        }

    } else if (method == 'POST') {
        //添加用户功能
        if (pathname == '/add') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.create(user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });

        } else if (pathname == '/modify') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.updateOne({ _id: query.id }, user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });
        }
    }

})

//监听端口
app.listen(3000);

(7)用户删除功能

const http = require('http');
const mongoose = require('mongoose'); //user文件夹中虽然没有mongose这个第三方模块,那么系统会自动去上一级目录database查找该模块,database下有node_modules,node_modules下有mongoose
const url = require('url');
const querystring = require('querystring');

//数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

//创建用户集合规则
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] //hobbies是一个数组,数组里面的值都要是字符串类型
});
//创建集合  返回集合的构造函数
const User = mongoose.model('User', userSchema);

//创建服务器
const app = http.createServer();
//为服务器端对象添加请求事件
app.on('request', async(req, res) => {
    //请求方式
    const method = req.method;
    //请求地址
    const { pathname, query } = url.parse(req.url, true);
    if (method == 'GET') {
        //呈现用户列表页面
        if (pathname == '/list') {
            //查询用户信息
            let users = await User.find();
            // console.log(users);是一个数组,数组中的元素是对象,每个对象中包含着每个用户的信息

            //将静态代码与查询到的数据进行拼接
            let list = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="/add" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>
            `;

            //对查询到的users数据进行循环操作,准备数据的拼接
            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="/remove?id=${item.id}" class="btn btn-danger btn-xs">删除</a>
                    <a href="\modify?id=${item.id}" class="btn btn-success btn-xs">修改</a>
                </td>
            </tr>`;
            });

            list += `
            </table>
                    </div>
                </body>
                </html>
            `;
            //将list变量响应给客户端
            res.end(list);
        } else if (pathname == '/add') {
            let add = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>添加用户</h3>
                    <form method='post' active="/add">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="足球" name="hobbies"> 足球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="篮球" name="hobbies"> 篮球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
                            </label>
                            <label class="checkbox-inline">
                            <input type="checkbox" value="烫头" name="hobbies"> 烫头
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">添加用户</button>
                    </form>
                </div>
            </body>
            </html>
                    `;
            res.end(add);
        } else if (pathname == '/modify') {
            let user = await User.findOne({ _id: query.id }); //返回一个对象,下面将对象中的参数与html文件进行拼接
            let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头'];
            console.log(user);

            let modify = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>修改用户</h3>
                    <form method='post' active="/modify?id=${user._id}">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" placeholder="请填写用户名" name="name" value="${user.name}">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" placeholder="请输入密码" name="password" value="${user.password}">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="请填写邮箱" name="age" value="${user.age}">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" placeholder="请填写邮箱" name="email" value="${user.email}">
                    </div>
                    <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                        
                    `;

            hobbies.forEach(item => {
                //判断当前循环项是否在用户数组里
                let isHobby = user.hobbies.includes(item);
                if (isHobby) {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies" checked> ${item}
                    </label>
                    `;
                } else {
                    modify += `
                    <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies"> ${item}
                    </label>
                    `;
                }
            });
            modify += `
            </div>
                    </div>
                    <button type="submit" class="btn btn-primary">修改用户</button>
                    </form>
                </div>
            </body>
            </html>
            `;
            res.end(modify);
        } else if (pathname == '/remove') {
            // res.end(query.id);
            await User.findOneAndDelete({ _id: query.id });
            //删除成功后重定向到列表页面
            res.writeHead(301, {
                Location: '/list'
            });
            res.end();
        }

    } else if (method == 'POST') {
        //添加用户功能
        if (pathname == '/add') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.create(user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });

        } else if (pathname == '/modify') {
            //接收用户提交的信息  post是一段一段地接收用户提交的信息
            let formData = '';
            //接收post参数
            req.on('data', param => {
                formData += param;
            });
            //post参数接收完毕
            req.on('end', async() => {
                let user = querystring.parse(formData);
                //将用户提交的信息添加到数据库中
                await User.updateOne({ _id: query.id }, user);
                //用户添加成功后重定向到列表页
                //重定向的状态码是301
                res.writeHead(301, {
                    //要调转的地方
                    Location: '/list'
                });
                res.end();
            });
        }
    }

})

//监听端口
app.listen(3000);
posted @ 2020-04-04 13:43  deer_cen  阅读(391)  评论(0编辑  收藏  举报