简体   繁体   English

MongoDb mongoose aggregatePagination 在不同的页面上返回多个相同的文档

[英]MongoDb mongoose aggregatePagination returns multiple same documents over different pages

I am facing an issue with mongodb and mongoose with pagination.我正面临着 mongodb 和 mongoose 的分页问题。 I am trying to query over a set of Tutors and get those who are matching the query in a paginated and sorted (by updatedDate) result.我正在尝试查询一组导师,并在分页和排序(按更新日期)结果中获取与查询匹配的导师。 But the fact is I get multiple same documents over different pages ... I would like it to return a set of unique documents.但事实是我在不同的页面上得到多个相同的文档......我希望它返回一组独特的文档。 Here is part of my function (the rest is just to build the query from the request body):这是我的功能的一部分(其余部分只是从请求正文构建查询):

exports.search = (req, res) => {

    var options = { page: page, limit: perPage, sortBy: { updatedDate: -1 }}

    const aggregate = Tutor.aggregate([
  {
    "$geoNear":
      {
        "near":
          {
            "type": "Point",
            "coordinates": [lon1, lat1]
          },
        "distanceField": "distance",
        "spherical": true,
        "maxDistance": radius
      }
  },
  {
    $match: match
  }
]);

Tutor
.aggregatePaginate(aggregate, options, function (err, result, pageCount, count) {
  if (err) {
    return res.status(400).send(err);
  }
  else {
    var opts = [
      { path: 'levels', select: 'name' },
      { path: 'subjects', select: 'name' },
      { path: 'assos', select: 'name' }
    ];
    Tutor
      .populate(result, opts)
      .then(result2 => {
        return res.send({
          page: page,
          perPage: perPage,
          pageCount: pageCount,
          documentCount: count,
          tutors: result2
        });
      })
      .catch(err => {
        return res.status(400).send(err);
      });
  }
})
};

Now, imagine I am querying page 1 with a limit per page of 8. I 've got back my 8 documents correctly, all different.现在,假设我正在查询第 1 页,每页限制为 8。我已经正确取回了我的 8 个文档,所有文档都不同。 But when I am querying page 2, with the same limit per page, half of the documents were already returned in page 1 !但是当我查询第 2 页时,每页具有相同的限制,一半的文档已经在第 1 页中返回! Would you know why is that so ?你知道为什么会这样吗? Thank you !谢谢 !

EDIT编辑

I figured it was the sortBy that makes it happen.我认为是sortBy让它发生了。 If i remove it, everything works correctly.如果我删除它,一切正常。 I need it though ...虽然我需要它...

After doing alot of research.经过大量研究。 I found this solution.我找到了这个解决方案。 Hope it will solve your issue.希望它能解决你的问题。

Jobs.aggregatePaginate(aggregateQuery, { page: 1, limit: 10, sort: { 'createdAt': 'desc' } }, function (){});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM