MongoDB之node操作实现数据库增删改查

2024-01-05 12:47:05 浏览数 (1)

代码语言:javascript复制
 大家好 我是歌谣 今天给大家带来的是MongoDB关于node操作数据库的讲解

依赖配置

代码语言:javascript复制
需要安装express-genetator脚手架创建项目

配置文件

代码语言:javascript复制
{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "ejs": "~2.6.1",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "mongoose": "^7.6.3",
    "morgan": "~1.9.1"
  }
}

文件目录

index.ejs

代码语言:javascript复制
<!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/add", {
        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/update/653f7be831c2cf3a58098d25", {
        method: "POST",
        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/delete/653f7be831c2cf3a58098d25").
        then(res => res.json()).then(res => {
          console.log(res)
          listUpdate()
        })
    }
    function listUpdate(){
      fetch("/api/user/list").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>

users.js

代码语言:javascript复制
var express = require('express');
const UserModel = require('../model/UserModel');
var router = express.Router();


/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
router.post('/user/add', function (req, res, next) {
  const { username, password, age } = req.body
  UserModel.create({
    username,
    password,
    age
  }).then(data => {
    console.log(data, "data is")
  })
  //插入数据库
  res.send({
    ok: 1
  })
});
router.post('/user/update/:id', function (req, res, next) {
  const { username, age, password } = req.body
  UserModel.updateOne({ _id: req.params.id },{username}).then(data => {
    res.send({
      ok: 1
    })
  })
});
router.get('/user/delete/:id', function (req, res, next) {
  const { username, age, password } = req.body
  UserModel.deleteOne({ _id: req.params.id }).then(data => {
    res.send({
      ok: 1
    })
  })


});
router.get('/user/list', function (req, res, next) {
  const { username, age, password } 
  = req.body
  UserModel.find({},["username","age"]).sort({age:-1}).then(data=>{
    res.send(data)
  })


});


module.exports = router;

UserMode.js

代码语言:javascript复制
const { Schema } = require("mongoose")
const mongoose=require("mongoose")
const UserType={
    username:String,
    password:String,
    age:Number
}


const UserModel=mongoose.model("user",new Schema(UserType))
module.exports=UserModel

app.js

代码语言:javascript复制
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', indexRouter);
app.use('/api', usersRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};


  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;

启动

代码语言:javascript复制
npm run start

0 人点赞