一个前端,爱跑步、爱吉他、爱做饭、爱生活、爱编程、爱南芳姑娘,爱我所爱。世间最温暖又无价的是阳光、空气与爱,愿它们能带你去更远的地方。

  • 文章
  • 心情
  • 照片墙
  • 留言板
  • 工具
  • 友链
  • biaoblog

    专注web开发技术分享

    mongoose根据id获取上、下相邻数据详情

    技术 225 2022-04-06 16:50

    废话不多说,这个就是为了实现 文章的上一篇和下一篇的接口

    直接上代码:

    router.post("/bookInfo", async (ctx) => {
      let bookId = ctx.request.body.ID;
      const book = mongoose.model("book");
    
      // 获取上一篇和下一篇的文章
      // select是指定返回的字段
      let prevBook = await book
        .findOne({ ID: { $lt: bookId }, visible: true })
        .sort({ ID: -1 })
        .select({ ID: 1, title: 1 })
        .then((res) => res);
      let nextBook = await book
        .findOne({ ID: { $gt: bookId }, visible: true })
        .sort({ ID: 1 })
        .select({ ID: 1, title: 1 })
        .then((res) => res);
      await book
        .findOne({ ID: bookId })
        .exec()
        .then((res) => {
          ctx.body = { code: 200, message: res, prevBook, nextBook };
        })
        .catch((err) => {
          ctx.body = { code: 500, message: err };
        });
    });
    

    参考:https://blog.csdn.net/u012914342/article/details/113518097

    $ne的使用:

    在find的条件中 不匹配某个结果

    let boardMsgLength = await messageBoard.find({ from: "留言板" }).count(); //匹配留言板的数量
    let booksMsgLength = await messageBoard  // 匹配非留言板的数量 且 根据ID查询
        .find({ from: { $ne: "留言板" }, ID: MessageBoardId })
        .count();
    


    文章评论

    评论列表(0