如何获得Mongoose文件的数量?

我正在研究一个Nodejs / Express / Mongoose应用程序,我想通过增加logging文件的数量来实现一个自动增量IDfunction,但是我不能得到这个计数,因为Mongoose“count”方法没有返回号码:

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

有人设法得到伯爵? 请帮助。

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

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

你也可以在find()之后尝试链接它:

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

更新:

正如@Creynders所build议的那样,如果你正在尝试实现一个自动增量值,那么值得看一下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 }); }); }); 

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

 const number = await Model.count({}); console.log(number); 

你需要等待callback函数

 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') 

看起来你期望var number包含计数值。 在你的callback函数中,你正在返回count但是这是asynchronous执行的,所以不会赋值给任何东西。

此外,您的callback函数中的第一个参数应该是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