如何获取Mongoose文件的数量?

kai*_*zer 18 mongoose mongodb node.js

我正在研究Nodejs/Express/Mongoose应用程序,我想通过增加记录文档的数量来实现自动增量ID功能,但是我无法得到这个数,因为Mongoose'count'方法没有返回号码:

var number = Model.count({}, function(count){ return count;});
Run Code Online (Sandbox Code Playgroud)

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

chr*_*dam 33

count函数是异步的,它不会同步返回一个值.用法示例:

Model.count({}, function(err, count){
    console.log( "Number of docs: ", count );
});
Run Code Online (Sandbox Code Playgroud)

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

Model.find().count(function(err, count){
    console.log("Number of docs: ", count );
});
Run Code Online (Sandbox Code Playgroud)

更新:

正如@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 

        });
    });
});
Run Code Online (Sandbox Code Playgroud)


Vas*_*iak 7

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

const number = await Model.countDocuments();
console.log(number);
Run Code Online (Sandbox Code Playgroud)


Len*_*eph 5

如果有人在2019年办理登机手续,count则不建议使用。而是使用countDocuments

例:

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