前端歌谣-第陆拾玖课-MongoDB之node操作实现数据库增删改查
  iHT0TLzU167T 2023年12月31日 12 0


前言

大家好 我是歌谣 今天给大家带来的是MongoDB关于node操作数据库的讲解

依赖配置

需要安装express-genetator脚手架创建项目

配置文件

{
  "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"
  }
}

文件目录

前端歌谣-第陆拾玖课-MongoDB之node操作实现数据库增删改查_javascript

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/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

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

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

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;

启动

npm run start

前端歌谣-第陆拾玖课-MongoDB之node操作实现数据库增删改查_用户名_02


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月31日 0

暂无评论

推荐阅读
iHT0TLzU167T