[Node.js] mongodb 增删查改

代码

mydb.js (用来定义表结构、连接数据库)

const mongoose = require('mongoose')

// 连接数据库 :mongo_test
mongoose.connect('mongodb://localhost:27017/mongo_test', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })

// 定义 User 表字段
const User = mongoose.model('User', new mongoose.Schema({
    name: { type: String ,unique: true},            // 禁止重名
    password: {                                                     
        type: String, set(val) {                                // 密文存储 , 10 代表密码强度
            return require('bcrypt').hashSync(val,10)
        }
    },
}))

// 导出 User 表对象
module.exports = { User }

app.js (实现增删查改功能)

'use strict';

const express = require('express')
const bodyParser = require('body-parser')
const { User } = require('./mydb')

// 创建服务器
const app = express()

// 初始化 bodyParser
app.use(bodyParser.urlencoded({ extend: false }));
app.use(bodyParser.json());

// 打印全部用户信息
app.post('/display', async (req, res) => {
    const user = await User.find()
    res.send(user)
})

// 注册(增)
app.post('/register', async (req, res) => {
    const user = await User.create({
        name: req.body.name,
        password: req.body.password,
    })

    res.send('注册成功')
})

// 登陆(查)
app.post('/login', async (req, res) => {
    const user = await User.findOne({
        name: req.body.name
    })
    if (!user) {
        return res.status(422).send({
            message: '用户不存在'
        })
    }

    const isPassVailed = require('bcrypt').compareSync(req.body.password, user.password)
    if (!isPassVailed) {
        return res.status(422).send({
            message: '密码错误'
        })
    }

    res.send('登陆成功')
})

// 重置密码(改)
app.post('/reset', async (req, res) => {
    const user = await User.findOne({
        name: req.body.name
    })
    if (!user) {
        return res.status(422).send({
            message: '用户不存在'
        })
    }

    const newPassword = req.body.password
    user.password = newPassword
    user.save()

    res.send('密码修改成功')
})

// 删除用户(删)
app.post('/delete', async (req, res) => {
    const user = await User.findOne({
        name: req.body.name
    })
    if (!user) {
        return res.status(422).send({
            message: '用户不存在'
        })
    }

    user.remove();

    res.send('删除成功')
})

// 处理 404 页面
app.use((req, res, next) => {
    res.status(404).send('404 not found')
})

// 监听端口
app.listen(3000, () => {
    console.log('server start ...')
})

参考资料

https://www.cnblogs.com/woodk/p/6155955.html

原文地址:https://www.cnblogs.com/csnd/p/15613307.html