Find and Count elements of collection with Mongoos

2019-01-26 00:13发布

问题:

In Mongoose, I need to find elements in a collection and count them, and getting both the results of the find and count. I have tried

Model.find().count(function (err, count) {
    // Get count, but cannot get results of find
});

Is there a way to get both find() and count() without calling them twice?

回答1:

You can use the length of the returned array:

Model.find().exec(function (err, results) {
  var count = results.length

});


回答2:

You have to do 2 separate queries unfortunately. Festo's answer only works if you have less elements in the database than the limit.

var countQuery = Model.count();
var findQuery = Model.find().limit(2);

countQuery.exec(function (e, count) {
  console.log('count', count); // can be more than 2, this is not calculated, mongo stores this value internally
})
findQuery.exec(function(e, data) {
  console.log('found items', data); // will be 2 or less elements
});


回答3:

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

  SomeModel.countDocuments({}, function(err, count) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(count)
    //and do some other fancy stuff
})

or

SomeModel
.estimatedDocumentCount()
.then(count => {
    console.log(count)
    //and do one super neat trick
})
.catch(err => {
    //handle possible errors
})