【发布时间】:2016-05-28 09:31:35
【问题描述】:
在 Mongoose 中,我需要在集合中查找元素并对其进行计数,并同时获取查找和计数的结果。我试过了
Model.find().count(function (err, count) {
// Get count, but cannot get results of find
});
有没有办法在不调用两次的情况下同时获取 find() 和 count()?
【问题讨论】:
在 Mongoose 中,我需要在集合中查找元素并对其进行计数,并同时获取查找和计数的结果。我试过了
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
});
【讨论】:
Model.find({}, function(err, results) {}),检查这个:mongoosejs.com/docs/api.html#model_Model.find
.count() 作为附加调用的情况下,大结果中的计数是有效的。只有在“分页”时才需要它。当你当然应该总是使用两个查询时。一个用于完整计数,另一个用于当前页面。
很遗憾,您必须执行 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
});
【讨论】:
query.skip(100).limit(50) 您跳过前 2x50 并显示第三批 50 个结果。
正如猫鼬文档和本杰明的回答中所述,不推荐使用 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
})
【讨论】:
您也可以使用mongoose-paginate plugin。
例如:
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
});
【讨论】:
DeprecationWarning:collection.count 已弃用,将在未来版本中删除。请改用 Collection.countDocuments 或 Collection.estimatedDocumentCount。 希望此更新对某人有所帮助。 示例:
var user = await User.find().countDocuments()
【讨论】: