前端歌谣-第柒拾课-MongoDB之node操作实现数据库增删改查(MVC模式)

发布时间:2023年12月28日

前言

大家好 我是歌谣 今天继续给大家带来node操作MongoDB实现数据库的增删改查操作的mvc版本

目录结构

在这里插入图片描述

control层

const UserService = require("../services/UserService")

const UserController = {
    addUser: async (req, res, next) => {
        const { username, password, age } = req.body
        await UserService.addUserService(username, password, age)
        //插入数据库
        res.send({
            ok: 1
        })
    },
    updateUser: async (req, res, next) => {
        const { username, age, password } = req.body
        await UserService.updateUserService(req.params.id, req.params.username, req.params.age, req.params.password)
        res.send({
            ok: 1
        })
    },
    deleteUser: async (req, res, next) => {
        const { username, age, password } = req.body
        await UserService.deleteUserService(req.params.id)
        res.send({
            ok: 1
        })
    },
    getUser:async(req, res)=>{
        const { username, age, password } 
        = req.body
        let data=await UserService.getUserSerice()
        console.log(data,"geyao is ")
        res.send(data)
      
      }
}
module.exports = UserController

service层

const UserModel = require("../model/UserModel")

const UserService = {
    addUserService: (username, password, age) => {
        return UserModel.create({
            username, password, age
        }).then(data => {
            console.log(data)
        })
    },
    updateUserService: (_id, username, age, password) => {
        return UserModel.updateOne({ _id: _id }, { username }).then(data => {
            console.log(data)
        })
    },
    deleteUserService: (_id) => {
        return UserModel.deleteOne({ _id: req.params.id }).then(data => {
            console.log(data)
        })
    },
    getUserSerice() {
        return UserModel.find({}, ["username", "age"]).sort({ age: -1 })
    }
}
module.exports = UserService

Route

var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
router.post('/user',UserController.addUser);
router.put('/user/:id',UserController.updateUser);
router.delete('/user/:id', UserController.deleteUser);
router.get('/user',UserController.getUser );

module.exports = router;

index.ejs

<!DOCTYPE html>
<html>

<head>
  <title>
    <%= title %>
  </title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
</head>

<body>
  <h1>
    mongodb的增删改查的显示
  </h1>
  <div>
    <div>用户名:<input id="username" /></div>
    <div>密码:<input type="password" id="password" /></div>
    <div>年龄:<input type="number" id="age" /></div>
    <div><button id="register">注册</button></div>
  </div>
  <hr>
  <div><button id="update">更新</button>
    <button id="remove">删除</button>
  </div>
  <hr>
  <table border="1">
    <thead>
      <tr>
        <td>id</td>
        <td>用户名</td>
        <td>年龄</td>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <script>
    var username = document.querySelector("#username")
    var password = document.querySelector("#password")
    var age = document.querySelector("#age")
    var register = document.querySelector("#register")
    var update = document.querySelector("#update")
    var remove = document.querySelector("#remove")
    register.onclick = function () {
      console.log(username.value, password.value, age.value)
      fetch("/api/user", {
        method: "POST",
        body: JSON.stringify({
          username: username.value,
          password: password.value,
          age: age.value
        }),
        headers: {
          "Content-type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
        listUpdate()
      })
    }
    update.onclick = function () {
      console.log(username.value, password.value, age.value)
      fetch("/api/user/65406b27f49dbc6f3034f8d0", {
        method: "PUT",
        body: JSON.stringify({
          username: username.value,
          password: password.value,
          age: "1"
        }),
        headers: {
          "Content-type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
        listUpdate()
      })
    }
    remove.onclick = function () {
      console.log(username.value, password.value, age.value)
      fetch("/api/user/65406b27f49dbc6f3034f8d0",{
        method:"DELETE"
      }).
        then(res => res.json()).then(res => {
          console.log(res)
          listUpdate()
        })
    }
    function listUpdate(){
      fetch("/api/user").then(res => res.json()).then(res => {
      console.log(res)
      var tbody = document.querySelector("tbody")
      tbody.innerHTML = res.map(item => `
      <tr>
        <td>${item._id}</td>
        <td>${item.username}</td>
        <td>${item.age}</td>
        </tr>
      `).join("")
    })
    }
    listUpdate()
    
  </script>
</body>

</html>

运行结果

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_41632427/article/details/134136321
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。