//创建http连接
const http = require('http');
//创建服务器
const app = http.createServer();
//第三方模块导入
const mongoose = require('mongoose');
//获取连接
const url = require('url');
//数据库连接地址
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: 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]
});
//创建集合
const User = mongoose.model('User', userSchema);
//添加属性事件
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"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></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.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="">删除</a>|<a href="">修改</a></td></tr>`;})list += ` </table></div></body></html>`res.end(list);}} else if (method == 'POST') {}url.parse(req.url);res.end('ok');
})
app.listen(3000);
运行结果