学习笔记 内容待商榷 欢迎提出宝贵意见
实现用户添加信息功能
1.连接数据库 建立服务器 建立集合规则
const http = require('http')
const mongoose = require('mongoose')
const url = require('url')
const querystring = require('querystring')
const app = http.createServer()
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, 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: { type: String },
email: { type: String },
hobbies: [String]
})
2.通过 mongoimport -d -c --file 往user集合中添加信息之后 下面代码表示的是把user的那个集合存到User里 (个人理解) 如果没有users这个集合的话 User.create({})相当于创建
const User = mongoose.model('User', userSchema)
3.服务器添加requset事件 下面是一个页面 请求地址是'/list' 点击添加用户 之后 跳转到请求地址为'/add'的页面
注释解释都在代码里
app.on('request', async(req, res) => {
let method = req.method; //获取请求类型
let { pathname } = new URL(req.url, 'http://localhost:3000') //获取请求地址
if (method == 'GET') {
//呈现页面
if (pathname == '/list') {
//查询用户信息
let users = await User.find()
//页面存到变量里 响应给客户端 html 字符串
let