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

时间:2016-02-16 21:58:24

标签: node.js mongodb mongoose

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

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

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

5 个答案:

答案 0 :(得分:12)

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

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

});

答案 1 :(得分:4)

不幸的是,您必须进行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
});

答案 2 :(得分:1)

如猫鼬文档和本杰明的答案中所述,不建议使用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
})

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

答案 3 :(得分:0)

您也可以使用mongoose-paginate plugin

例如:

:remote connect tinkerpop.server conf/remote.yaml session

答案 4 :(得分:0)

DeprecationWarning:不建议使用collection.count,并且在以后的版本中将其删除。请改用Collection.countDocuments或Collection.estimatedDocumentCount。 希望此更新对某人有所帮助。 例子:

var user =等待User.find()。countDocuments()

相关问题