Reputation: 14750
I'm building pagination with mongoose/nodejs application and have the following code:
var Query = Model.find(
"location": {
"$geoWithin": {
"$box": [
[165.8694369, -52.61941849999999],
[175.831536, -29.2313419]
]
}
}
});
// Get count of documents
return Query.count(function (err, totalCount) {
if (err) throw err;
// Get paginated list
return Query.
find().
skip(skip).
limit(limit).
exec(function (err, results) {
if (err) throw err;
// return result
});
In the preceding code I get totalCount
to build pagination on client-side and it works fine. But now I need to use aggregate
instead find
and trying the following:
// Construct pipeline
var pipeline = [{
"$geoNear": {
"near": [165.8694369, -52.61941849999999],
"distanceField": "distance"
}
}];
var Query = adModel.aggregate(pipeline);
// Get count of documents
return Query.count(function (err, totalCount) {
if (err) throw err;
But unfortunately I get the error count() method does not exists
. How could I total count of documents with aggregation framework?
Upvotes: 0
Views: 1558
Reputation: 191
The problem is that Model.aggregate doesn't return a Query object that's why the count
method does not exists.
Anyway since it returns a promise you can count your docs like this:
adModel.aggregate(pipeline).then(function (docs) {
console.log(docs.length);
});
and if you don't like promises you can still pass a callback:
adModel.aggregate(pipeline, function (err, docs) {
console.log(docs.length);
});
Upvotes: 2