I am facing an issue with mongodb and mongoose with pagination. 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. But when I am querying page 2, with the same limit per page, half of the documents were already returned in page 1 ! Would you know why is that so ? Thank you !
EDIT
I figured it was the sortBy that makes it happen. 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 (){});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.