簡體   English   中英

使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 查找和計數集合元素

[英]Find and Count elements of collection with Mongoose

在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中,我需要在集合中查找元素並對其進行計數,並獲取查找和計數的結果。 我努力了

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

有沒有辦法在不調用兩次的情況下同時獲得 find() 和 count() ?

您可以使用返回數組的長度:

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

});

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

正如貓鼬文檔和本傑明的回答中所述,不推薦使用 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
})

您也可以使用貓鼬分頁插件

例如:

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
});

棄用警告:collection.count 已棄用,將在未來版本中刪除。 請改用 Collection.countDocuments 或 Collection.estimatedDocumentCount。 希望此更新對某人有所幫助。 例子 :

var user = await User.find().countDocuments()

只是一種更好的寫作方式

try{
   let result = await Model.find();
   console.log(result); //result
   console.log(result.length); //count
} catch(err){
   //error
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM