淘先锋技术网

首页 1 2 3 4 5 6 7

一. 准备部分

1.开启MongoDB数据库服务 E:\webLearn\mongodb4.1.7\bin>.\mongo.exe 

2.打开 navicat 连接数据库服务

3.新建数据库myProject,新建集合users

4.新建Express 应用程序生成器(需要有node环境),cmd进入命令行窗口,输入 

//  Node.js 8.2.0 及更高版本中
npx express-generator

// 旧版本中
npm install -g express-generator

// 创建myapp
express myapp --view=ejs

myapp骨架目录结构 

 5.项目连接数据库,在myapp文件夹的根目录下创建config文件夹,创建文件db.config.js,写代码

const mongoose = require("mongoose")
mongoose.connect("mongodb://127.0.0.1:27017/myProject")

6.引入数据库模块,在bin文件夹的www文件中,写代码

require('../config/db.config')

7.因为MongoDB比较自由,所以往数据库里存数据时需要加一些限制,创建model文件夹,创建UserModel.js文件,写代码

// 引入mongoose
const mongoose = require('mongoose')

// 设置字段类型
const Schema=mongoose.Schema
const UserType = {
  username: String,
  password: String,
  age:Number
}

// 模型 user 将会对应 users 集合
const UserModel = mongoose.model("user",new Schema(UserType))

// 导出
module.exports=UserModel

二. 前端部分

1.打开views文件夹,将默认创建的index.ejs文件清空,写代码(删除layout.ejs文件)

<!DOCTYPE html>
<html >

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <h1>mongodb增删改查</h1>
    <div>
      <div>用户名:<input type="text" id="username"></div>
      <div>密码:<input type="password" id="password"></div>
      <div>年龄:<input type="number" id="age"></div>
    </div>
    <button id="register">注册</button>
    <hr>
    <button id="update">更新</button>
    <hr>
    <button id="delete">删除</button>
    <hr>
    <button id="search">查询</button>
  </div>
  <script>
    var username = document.querySelector('#username')
    var password = document.querySelector('#password')
    var age = document.querySelector('#age')
    var registerFun = document.querySelector('#register')
    var updateFun = document.querySelector('#update')
    var deleteFun = document.querySelector('#delete')
    var searchFun = document.querySelector('#search')

    // 增
    registerFun.onclick = () => {
      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);
      })
    }

    // 删
    deleteFun.onclick = () => {
      fetch("/api/user/62e748cf332656d2c168621b", {
        method: "DELETE",
      }).then(res => res.json()).then(res => {
        console.log(res);
      })
    }

    // 改
    updateFun.onclick = () => {
      fetch("/api/user/62e748cf332656d2c168621b", {
        method: "PUT",
        body: JSON.stringify({
          username: "宵宫",
          password: "密码",
          age: 1,
        }),
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res);
      })
    }

    // 查
    searchFun.onclick = () => {
      fetch("/api/user/?page=2&limit=2", {
        method: 'GET'
      }).then(res => res.json()).then(res => {
        console.log(res);
      })
    }
  </script>
</body>

</html>

 2.前端页面显示

三. 后端部分

1. 打开package.json,将scripts改成以下代码(需要安装nodemon自动重启服务)

"scripts": {
    "start": "nodemon ./bin/www"
  },

2.打开app.js

将默认的 app.use('/users', usersRouter);

改成 app.use('/api', usersRouter);

3.打开routes文件夹下的users.js文件,写代码

var express = require('express')
// 引入控制器文件 
const UserController = require('../controller/UserController')
var router = express.Router()

// 增
router.post('/user/', UserController.addUser)

// 删
router.delete('/user/:id', UserController.delUser)

// 改
router.put('/user/:id', UserController.putUser)

// 查 
router.get('/user/', UserController.getUser)

module.exports = router

4.创建controller文件夹,创建UserController.js文件,写代码

// 引入更改数据文件
const UserService = require("../service/UserService")

// 接收参数和返回参数
const UserController = {
  // 增
  addUser: (req, res, next) => {
  const { username, password, age } = req.body
    UserService.addUser( username, password, age)
    res.send({
      ok: 1
    })
  },
  // 删
  delUser: (req, res, next) => {
    const id=req.params.id
    UserService.delUser(id)
     res.send({
      ok: 1
    })
  },
  // 改
  putUser: (req, res, next) => {
    const id=req.params.id
    const { username, password, age} = req.body
    UserService.putUser( username, password, age, id)
    res.send({
      ok: 1
    })
  },
  // 查
  getUser:async (req, res, next) => {
    const { page, limit } = req.query
    const data=await UserService.getUser( page, limit )
    res.send(data)
  }
}

module.exports=UserController

5.创建service文件夹,创建UserService.js文件,写代码

// 操作数据库
const UserModel=require('../model/UserModel')
const UserService = {
  //增
  addUser:async ( username, password, age) => {
   await UserModel.create({
    username,
    password,
    age
   })
  },
  //删
  delUser: async (id) => {
   await UserModel.deleteOne({
      _id: id
    })
  },
  //改
  putUser: async ( username, password, age, id) => {
    await  UserModel.updateOne(
    { _id: id },
    {
      username,
      password,
      age
    }
  )
  },
  //查
  getUser: (page,limit) => {
    return UserModel.find({},["username","age"]).sort({age:1}).skip((page-1)*limit).limit(limit)
  }
}

module.exports=UserService

6.最后 npm start 运行文件,成功。 

总结:后端的逻辑是,通过routes文件导航路由接口,controller控制器文件去接收前端参数和返回给前端数据,service文件用来改变数据库里的数据。