一:声明Schemas(相当于在数据库上建立一个表)
const Person = require("./../dbs/models/person") //首先把这个模型引进来,
下图蓝线
开始操作数据库(增查改删):
增( save() ):
(上图红线部分)
router.post('/addPerson', async function (ctx) { //只允许post请求,async为后面的await 作准备
const person = new Person({ //给model新建一个实例
name: ctx.request.body.name, //从接口中来的name,注意body是post请求里面的,get请求用query
age: ctx.request.body.age //从接口中来的age
})
let code
try {
await person.save();
//这里要说明,Schema是声明表中有哪些字段,而要使用这些方法,是在model里面的方法,如save(),update(),remove()等等,去看文档吧
code=0
} catch (error) {
code=-1
}
ctx.body={ //返回去code的值,成功为0,失败-1
code
}
})
好,到这里就可以测试接口了
http://localhost:3000/users/addPerson
成功!
测试几口也可以用命令
$ curl -d “name=hanmeimei&age=27” http://localhost:3000/users/addPerson
查( find() ):
router.post('/getPerson', async function (ctx) {
const req = await Person.find({ name: ctx.request.body.name }) //model中的find()方法
let code
try {
if (JSON.stringify(req) === '[]') { //如果去找返回是个空数组,意思是没找到,code返回为-2
code = -2
}else{ //找到了返回0
code=0
}
} catch (error) { //报错返回-1
code = -1
}
ctx.body = {
code,
req
}
})
改( update() )
router.post('/updatePerson',async function(ctx){
let code
const result=await Person.where({
name:ctx.request.body.name
}).update({
age:ctx.request.body.age
})
try {
await result,
code=0
} catch (error) {
code=-1
}
ctx.body={
code,
result
}
})
删( remove() - - 但是一般不会使用删除,只是更改状态 )
router.post('/removePerson',async function(ctx){
//let code
const result = await Person.where({
name:ctx.request.body.name
}).remove()
ctx.body={
result
}
})
mongoose里面有很多高级的用法,建议去官网看
https://mongoosejs.com/docs/guide.html