Use express framework + mongodb to quickly build back-end projects

First of all, the node environment needless to say

Then we use express scaffolding express-generator

Quickly create project directories

Install express-generator globally

npm i -g express-generator
复制代码

Then use the express command to create the project, programnem is your project folder name

express <programname>
复制代码

Then we have a complete express project directory, enter the project folder ->

## 安装依赖
npm install

## 运行项目
npm run start
复制代码

Enter localhost:3000 in the browser, you can see the following interface

But we found that if we modify the file, the page will not change, it is necessary to restart npm start, this is because start is not a hot update.

At this point we can install nodemon dependencies and use nodemon to run our services

Install nodemon, and use

npm i -S nodemon
复制代码

Open package.json

旧代码
"scripts": {
  "start": "node ./bin/www"
},

新代码"scripts": {
  "dev": "nodemon ./bin/www",
  "start": "node ./bin/www"
},

增加了 ——> "dev": "nodemon ./bin/www",
复制代码

At this point we run  

npm run dev
复制代码

It is found that after modifying the code, the content of the page will change, and there is no need to re-run it.

So much said above, I found it a bit long-winded, but I want to make it as clear as possible.

Next I'm going to speed up.

Directory structure modification

I like to put the routes folder under a separate src folder. Under src, I usually create some other folders, as shown below

For comparison, I also created a new config folder outside to store public configurations, such as jwt signatures, appids and secret keys for applet logins, and so on.

Install and use mongodb database

The above is the creation of the directory structure, the next step is the database link, model operation

安装mongoose依赖
npm i -S mongoose
复制代码

Under the db folder, create a new mongodb.js

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

// 连接数据库,自动新建 ExpressApi 库
mongoose.connect('mongodb://localhost:27017/ExpressApi', {
  useNewUrlParser: true, // 避免“不建议使用当前URL字符串解析器”
  useCreateIndex: true, // 解决MongoDB弃用警告
  useUnifiedTopology: true, // 解决连接报错问题
  useFindAndModify: false
})

module.exports = mongoose
复制代码

Then we create a new model file under the model folder, such as User.js

Here it is recommended that the model file be named with a big hump

User.js

// 引入mongodb
const mongoose = require('../db/mongodb')
const bcrypt = require('bcrypt')
// 建立用户表
const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true
    },
    password: {
        type: String,
        set(val){
            return bcrypt.hashSync(val, 10)
        },
        select: false
    },
    createTime: {
        type: Date,
        default: Date.now
    },
    updateTime: {
        type: Date,
        default: Date.now
    }
})

// 建立用户数据库模型
const User = mongoose.model('User', UserSchema)
module.exports = { User }
复制代码

The most basic user model generally includes username and password, as well as creation time, update time,

bcrypt password encryption is also used here  

npm i -S bcrypt
复制代码

After the database model is created, we can use it in the route

For example, we use in routes/users.js

var express = require('express');
var router = express.Router();
const { User } = require('../model/User')

// 用户注册
router.post('/register', async (req, res, next) => {
  const user = await User.create({
    username: req.body.username,
    password: req.body.password
 }) 
 res.send(user)
});

// 获取用户信息
router.get('/info', async (req, res, next) => {
  const user = await User.findOne({
    _id: req.user_id  })
  res.send({
    code: 200,
    data: user
  })
})

// 获取用户列表
router.get('/list', async(req, res, next)=>{
  const user = await User.find()
  res.send({ 
   code: 200,
    msg: '获取成功',
    data: user
  })
})

module.exports = router;
复制代码

The above is the use of simple mongodb database

In order to verify that our code does work, we can use the interface debugging tool to test

Here I use vscode's plug-in REST Client for testing,

Vscode searches for the plug-in REST Client and installs it

Then create a new .http file in the root directory of the project

// test.http@url=http://localhost:3000

### 获取用户列表
get {
   
   {url}}/users/list

### 注册账号
POST {
   
   {url}}/users/register
Content-Type: application/json

{
  "username": "user3",
  "password": "123456"
}
复制代码

Above we have a simple basic project based on express+mongodb, and here are only examples of database operations for adding and querying.

Subsequent development is actually the code that realizes business functions. In fact, it is relatively simple. If you don’t know how to do it, you can also go to Baidu.

Author: Zen Yixia
Link: https://juejin.cn/post/6931253375195414535
Source: Rare Earth Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_45530512/article/details/130422927