node.js 使用猫鼬查找和计数集合元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35443821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:55:47  来源:igfitidea点击:

Find and Count elements of collection with Mongoose

node.jsmongodbmongoose

提问by Marc Bacvanski

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

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

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?

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

回答by Gergo

You can use the length of the returned array:

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

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

});

回答by user1695032

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

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

回答by SirPhemmiey

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:

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

or

或者

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

回答by Pulkit chadha

You can also use mongoose-paginate plugin.

你也可以使用猫鼬分页插件

For example:

例如:

Model.paginate({}, { offset: 100, limit: 0 }).then(function(result) {
      // result.docs - Array of documents
      // result.total - Total number of documents in collection that match a query
      // result.limit - 0
      // result.offset - 100
});