Paginate数组在文件mongodb聚合中

时间:2018-04-13 04:10:02

标签: mongodb mongoose aggregation-framework

我有用户集合,每个文档都有子文档(跟随/关注者),我想创建用于获取用户关注者的API

此查询工作正常,但我尝试制作一个分页结果,例如每页获得10个结果

{
        $match: { username: new RegExp(username, "i") }
      },
      {
        $unwind: "$followers"
      },
      {
        $lookup: {
          from: "users",
          localField: "followers",
          foreignField: "_id",
          as: "info"
        }
      },
      {
        $unwind: "$info"
      },
      {
        $project: {
          info: {
            _id: 1,
            username: 1,
            avatar: { $ifNull: ["$info.avatar", ""] },
            fullname: { $ifNull: ["$info.fullname", ""] },
            follow_status: {
              $cond: [{ $in: ["$info._id", "$followed"] }, 1, 0]
            }
          }
        }
      },
      {
        $replaceRoot: { newRoot: "$info" }
      } 

赞赏你的支持

解决方案

我使用https://github.com/NetanelBasal/paginate-array库在聚合阶段后对数组进行分页。

1 个答案:

答案 0 :(得分:0)

https://www.npmjs.com/package/mongoose-paginate这个插件库是我用来分页所有需要它的API调用的,它可以是超级基本的或超级复杂的,并且很容易插入到前端以及