项目准备
1、安装 node 和 koa2 安装方法自行百度网上有很多方法
2、安装包MongoDB 安装方法自行百度即可
3、安装mongoose: cnpm i mongoose
4、安装 Robo 3t 安装方法自行百度 这个是用来查看数据库的
连接数据库
新建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/ 命令行和控制台没有报错 表示连接成功
数据库的增删改查
增加数据
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
查询数据
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
更改数据
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
删除数据(一般不建议这么做,这里只是为了演示)
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 连接数据库
打开robo 3t 点击 “create a new connection ”,在serve输入数据库的地址,在port输入端口号即可
通过Robo 3t查看数据库是否完成相应的操作
谢谢观看,如有不足,敬请指教