使用Mongoose查找和计数集合的元素

mba*_*ski 3 mongoose mongodb node.js

在Mongoose中,我需要在集合中查找元素并对它们进行计数,并获得查找和计数的结果.我试过了

Model.find().count(function (err, count) {
    // Get count, but cannot get results of find
});
Run Code Online (Sandbox Code Playgroud)

有没有办法获得find()和count()而不调用它们两次?

Fes*_*sto 14

您可以使用返回数组的长度:

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

});
Run Code Online (Sandbox Code Playgroud)


use*_*032 5

不幸的是,您必须执行2个单独的查询。仅当数据库中的元素数少于限制时,Festo的答案才有效。

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
});
Run Code Online (Sandbox Code Playgroud)


Sir*_*iey 5

正如猫鼬文档和本杰明的回答中所述,不推荐使用 Model.count() 方法。除了使用 count(),替代方法如下:

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

或者

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