koa2 + MongoDB + mongoose + Robo 3T-Setting up a server

Insert picture description here

Project preparation
1、安装 node 和 koa2 安装方法自行百度网上有很多方法

2、安装包MongoDB 安装方法自行百度即可

3、安装mongoose:  cnpm i mongoose 

4、安装 Robo 3t 安装方法自行百度  这个是用来查看数据库的
Connect to the database
新建config.js文件用来配置数据库的连接内容如下

module.exports = ({
    
    

    dbs: "mongodb://127.0.0.1:27017/dbs"
    
})

在app.js中引入 并连接数据库

//引用数据源数据

const mongoose = require('mongoose');

const dbConfig = require('./dbs/config')

//连接数据库 这个配置写死即可

mongoose.connect(dbConfig.dbs, {
    
    

    useNewUrlParser: true
    
})

浏览器地址栏输入http://localhost:3000/  命令行和控制台没有报错 表示连接成功
Database addition, deletion, modification

Increase data

1、编写路由

router.post('/addPerson', async(ctx, done) => {
    
    

        const person = new Person({
    
    
        
            name: ctx.request.body.name,
            
            age: ctx.request.body.age
            
        })
        let code = 0
        try {
    
    
            await person.save();
            code = 0
        } catch (error) {
    
    
            code = -1
        }
        ctx.body = {
    
    
            code
        }
})

2、发起请求

在命令行输入: curl -d "name=loki&age=26" http://localhost:3000/users/addPerson

Query data

1、编写路由

router.post('/getPerson', async(ctx, done) => {
    
    

    const result1 = await Person.findOne({
    
     name: ctx.request.body.name })
    
    const result2 = await Person.find({
    
     name: ctx.request.body.name })
    
    ctx.body = {
    
     result1, result2, code: 0 }
    
})

2、发起请求

在命令行输入: curl -d "name=loki" http://localhost:3000/users/getPerson

Change data

1、编写路由

router.post('/updatePerson', async(ctx, done) => {
    
    

    const result = await Person.where({
    
    
    
        name: ctx.request.body.name
        
    }).update({
    
    
    
        age: ctx.request.body.age
        
    })
    ctx.body = {
    
    
    
        code: 0
    }
})

2、发起请求

在命令行输入: curl -d "name=add&age=110" http://localhost:3000/users/updatePerson

Delete data (generally not recommended, this is just for demonstration)

1、编写路由


router.post('/removePerson', async(ctx, done) => {
    
    

    const result = await Person.where({
    
    
    
        name: ctx.request.body.name
        
    }).remove({
    
    
    
        age: ctx.request.body.age
        
    })
    ctx.body = {
    
    
    
        code: 0
        
    }
})

2、发起请求

在命令行输入: curl -d "name=add" http://localhost:3000/users//removePerson
Robo 3t connects to the database

Open robo 3t and click "create a new connection", enter the address of the database in serve, and enter the port number in port

Check whether the database has completed the corresponding operation through Robo 3t

Thank you for watching, if there are any shortcomings, please advise

Guess you like

Origin blog.csdn.net/handsomezhanghui/article/details/108082586