电影收藏功能 movieCollect.js
const router = require("koa-router")()
const MovieModel = require("../../models/movie")
const UserModel = require("../../models/user")
router.post("/api/collectMovie/:m",async ctx=>{
var {m} = ctx.request.params
var {id,collected} = ctx.request.body
try{
var data = await MovieModel(m).updateOne({_id:id},{$set:{collected}})
if(data.nModified==0){
throw new Error(`${m}这个传值不合法`)
}else{
/* 添加收藏数据到user */
var item = await MovieModel(m).find({_id:id})
if(collected){
await UserModel.updateOne({},{$push:{collects:item[0]}})
ctx.body={
code:200,
msg:"收藏成功"
}
}else{
await UserModel.updateOne({},{$pull:{collects:{_id:id}}})
ctx.body={
code:200,
msg:"取消收藏"
}
}
}
}catch(err){
// id , collected 走catch
ctx.body={
code:400,
msg:"输入的参数不合法"
}
}
})
module.exports = router
文章收藏 ArticleCollect.js
const router = require("koa-router")()
const ArticleModel = require("../../models/article")
router.post("/api/articleCollect",async ctx=>{
var {id,collected} = ctx.request.body
try{
await ArticleModel.updateOne({_id:id},{$set:{collected}})
ctx.body={
code:200,
msg:"修改成功",
request:"POST /api/doCollect"
}
}catch(err){
ctx.body={
code:400,
msg:"请求参数不合法",
request:"POST /api/doCollect"
}
}
})
module.exports = router