解决方案的背景
正如猫鼬文档和本杰明的回答中所述,Model.count() 方法已被弃用。除了使用count(),替代方案如下:
Model.countDocuments(filterObject, callback)
计算有多少文档与集合中的过滤器匹配。传递一个空对象 {} 作为过滤器会执行完整的集合扫描。如果集合很大,可以使用下面的方法。
Model.estimatedDocumentCount()
此模型方法估计 MongoDB 集合中的文档数。这种方法比之前的countDocuments() 更快,因为它使用集合元数据而不是遍历整个集合。但是,正如方法名称所暗示的那样,根据数据库配置,结果是估计值,因为元数据可能无法反映方法执行时刻集合中文档的实际数量。
这两种方法都返回一个猫鼬查询对象,可以通过以下两种方式之一执行。如果您想稍后执行查询,请使用 .exec()。
解决办法
选项 1:传递回调函数
例如,使用.countDocuments() 计算集合中的所有文档:
someModel.countDocuments({}, function(err, docCount) {
if (err) { return handleError(err) } //handle possible errors
console.log(docCount)
//and do some other fancy stuff
})
或者,使用.countDocuments() 计算集合中具有特定名称的所有文档:
someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
//see other example
}
选项 2:使用.then()
猫鼬查询有.then(),所以它是“thenable”的。这是为了方便,查询本身并不是一个承诺。
例如,使用.estimatedDocumentCount() 计算集合中的所有文档:
someModel
.estimatedDocumentCount()
.then(docCount => {
console.log(docCount)
//and do one super neat trick
})
.catch(err => {
//handle possible errors
})
选项 3:使用异步/等待
当使用 async/await 方法时,recommended 方法是与 .exec() 一起使用,因为它提供了更好的堆栈跟踪。
const docCount = await someModel.countDocuments({}).exec();
通过 stackoverflowing 学习,