天天看點

[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 }      
'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 ...')
})