如何使用猫鼬获取文件数量?

How to get number of documents using Mongoose?

我正在开发一个 Nodejs/Express/Mongoose 应用程序,我想通过增加记录文档的数量来实现自动增量 ID 功能,但我无法获得此计数,因为 Mongoose 'count' 方法不 return 数字:

var number = Model.count({}, function(count){ return count;});

有人设法得到计数吗?请帮忙

计数函数是异步的,它不会同步 return 一个值。用法示例:

Model.count({}, function(err, count){
    console.log( "Number of docs: ", count );
});

您也可以尝试在 find():

之后链接它
Model.find().count(function(err, count){
    console.log("Number of docs: ", count );
});

更新(节点:25093 - 弃用警告):

不推荐使用计数,您也可以像使用“计数”一样使用“Collection.countDocuments”或“Collection.estimatedDocumentCount”。

更新:

正如@Creynders 所建议的,如果您正在尝试实现自动增量值,那么值得查看 mongoose-auto-increment 插件:

用法示例:

var Book = connection.model('Book', bookSchema);
Book.nextCount(function(err, count) {
 
    // count === 0 -> true 
 
    var book = new Book();
    book.save(function(err) {
 
        // book._id === 0 -> true 
 
        book.nextCount(function(err, count) {
 
            // count === 1 -> true 
 
        });
    });
});

您似乎希望 var number 包含计数值。在您的回调函数中,您返回 count 但这是异步执行的,因此不会将值分配给任何东西。

此外,回调函数中的第一个参数应该是 err

例如:

var number = Model.count({}, function(err, count) {
    console.log(count); // this will print the count to console
});

console.log(number); // This will NOT print the count to console

你必须等待回调函数

Model.count({}, function(err , count){
  var number = count;
  console.log(number);
});

在JavaScript

setTimeout(function() {
  console.log('a');
}, 0);

console.log("b");

"b" 将在 "a" 之前打印 因为

console.log('a')

如果您使用 node.js >= 8.0 和 Mongoose >= 4.0,您应该使用 await.

const number = await Model.countDocuments();
console.log(number);

如果有人在 2019 年签到,count 已弃用。相反,使用 countDocuments.

示例:

const count = await Model.countDocuments({ filterVar: parameter }); console.log(count);

如果您的 collection 很大 - 使用 Model.estimatedDocumentCount()。它比 countcountDocuments 快,因为它不会扫描整个 collection.

https://mongoosejs.com/docs/api/model.html#model_Model.estimatedDocumentCount