电影收藏功能 movieCollect.js

  1. const router = require("koa-router")()
  2. const MovieModel = require("../../models/movie")
  3. const UserModel = require("../../models/user")
  4. router.post("/api/collectMovie/:m",async ctx=>{
  5. var {m} = ctx.request.params
  6. var {id,collected} = ctx.request.body
  7. try{
  8. var data = await MovieModel(m).updateOne({_id:id},{$set:{collected}})
  9. if(data.nModified==0){
  10. throw new Error(`${m}这个传值不合法`)
  11. }else{
  12. /* 添加收藏数据到user */
  13. var item = await MovieModel(m).find({_id:id})
  14. if(collected){
  15. await UserModel.updateOne({},{$push:{collects:item[0]}})
  16. ctx.body={
  17. code:200,
  18. msg:"收藏成功"
  19. }
  20. }else{
  21. await UserModel.updateOne({},{$pull:{collects:{_id:id}}})
  22. ctx.body={
  23. code:200,
  24. msg:"取消收藏"
  25. }
  26. }
  27. }
  28. }catch(err){
  29. // id , collected 走catch
  30. ctx.body={
  31. code:400,
  32. msg:"输入的参数不合法"
  33. }
  34. }
  35. })
  36. module.exports = router

文章收藏 ArticleCollect.js

  1. const router = require("koa-router")()
  2. const ArticleModel = require("../../models/article")
  3. router.post("/api/articleCollect",async ctx=>{
  4. var {id,collected} = ctx.request.body
  5. try{
  6. await ArticleModel.updateOne({_id:id},{$set:{collected}})
  7. ctx.body={
  8. code:200,
  9. msg:"修改成功",
  10. request:"POST /api/doCollect"
  11. }
  12. }catch(err){
  13. ctx.body={
  14. code:400,
  15. msg:"请求参数不合法",
  16. request:"POST /api/doCollect"
  17. }
  18. }
  19. })
  20. module.exports = router