实现用户添加信息 修改信息 功能

学习笔记 内容待商榷 欢迎提出宝贵意见

实现用户添加信息功能

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
  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值