node.js 如何获得猫鼬模型的所有数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10811887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:47:02  来源:igfitidea点击:

How to get all count of mongoose model?

node.jsmongodbmongoose

提问by smilexu

How can I know the count of a model that data has been saved? there is a method of Model.count(), but it doesn't seem to work.

如何知道已保存数据的模型计数?有一种方法Model.count(),但似乎不起作用。

var db = mongoose.connect('mongodb://localhost/myApp');
var userSchema = new Schema({name:String,password:String});
userModel =db.model('UserList',userSchema);        
var userCount = userModel.count('name');

userCountis an Object, which method called can get a real count?

userCount是一个对象,调用哪个方法可以得到一个真正的count

Thanks

谢谢

回答by UpTheCreek

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

您的代码不起作用的原因是 count 函数是异步的,它不会同步返回值。

Here's an example of usage:

下面是一个使用示例:

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

回答by almypal

The code below works. Note the use of countDocuments.

下面的代码有效。注意countDocuments的使用。

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 

回答by Moh .S

You should give an object as argument

你应该给一个对象作为参数

userModel.count({name: "sam"});

or

或者

userModel.count({name: "sam"}).exec(); //if you are using promise

or

或者

userModel.count({}); // if you want to get all counts irrespective of the fields

On the recent version of mongoose, count() is deprecated so use

在 mongoose 的最新版本中,count() 已被弃用,因此请使用

userModel.countDocuments({name: "sam"});

回答by Benjamin

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocumentsor collection.estimatedDocumentCountinstead.

collection.count 已弃用,将在未来版本中删除。使用集合。计数文档或集合。而是估计文档计数。

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

回答by heilala

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count()is deprecated. Instead of using count(), the alternatives are the following:

正如猫鼬文档和本杰明的回答中所述,不推荐使用Model.count()方法。除了使用 count(),替代方法如下:

Model.countDocuments(filterObject, callback)

Model.countDocuments(filterObject, 回调)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

计算集合中与过滤器匹配的文档数。传递一个空对象 {} 作为过滤器会执行一个完整的集合扫描。如果集合很大,可能会使用以下方法。

Model.estimatedDocumentCount()

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

此模型方法估计 MongoDB 集合中的文档数量。此方法比之前的 countDocuments() 更快,因为它使用集合元数据而不是遍历整个集合。但是,正如方法名称所暗示的那样,根据数据库配置,结果是一个估计值,因为元数据可能无法反映方法执行时刻集合中文档的实际数量。

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

这两种方法都返回一个 mongoose 查询对象,可以通过以下两种方式之一执行。如果您想稍后执行查询,请使用 .exec()。

1) Pass a callback function

1)传递回调函数

For example, count all documents in a collection using .countDocuments():

例如,使用 .countDocuments() 计算集合中的所有文档:

SomeModel.countDocuments({}, function(err, count) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(count)
    //and do some other fancy stuff
})

Or, count all documents in a collection having a certain name using .countDocuments():

或者,使用 .countDocuments() 计算集合中具有特定名称的所有文档:

SomeModel.countDocuments({ name: 'Snow' }, function(err, count) {
    //see other example
}

2) Use .then()

2) 使用 .then()

A mongoose query has .then() so it's “thenable”. This is for a convenience and query itself is not a promise.

猫鼬查询有 .then() 所以它是“thenable”的。这是为了方便起见,查询本身不是承诺。

For example, count all documents in a collection using .estimatedDocumentCount():

例如,使用 .estimatedDocumentCount() 计算集合中的所有文档:

SomeModel
    .estimatedDocumentCount()
    .then(count => {
        console.log(count)
        //and do one super neat trick
    })
    .catch(err => {
        //handle possible errors
    })

Hope this helps!

希望这可以帮助!

回答by Mridul Tripathi

The highest voted answers here are perfectly fine I just want to add up the use of awaitso that the functionality asked for can be archived:

这里投票最高的答案非常好,我只想添加await的使用,以便可以存档要求的功能:

const documentCount = await userModel.count({});
console.log( "Number of users:", documentCount );

It's recommended to use countDocuments()over 'count()' as it will be deprecated going on. So, for now, the perfect code would be:

建议在 'count()'上使用countDocuments(),因为它将被弃用。所以,就目前而言,完美的代码是:

const documentCount = await userModel.countDocuments({});
console.log( "Number of users:", documentCount );

回答by debeka

As said before, you code will not work the way it is. A solution to that would be using a callback function, but if you think it would carry you to a 'Callback hell', you can search for "Promisses".

如前所述,您的代码不会按原样工作。一个解决方案是使用回调函数,但如果你认为它会让你进入“回调地狱”,你可以搜索“Promisses”。

A possible solution using a callback function:

使用回调函数的可能解决方案:

//DECLARE  numberofDocs OUT OF FUNCTIONS
     var  numberofDocs;
     userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

if you want to search the number of documents based on a query, you can do this:

如果要根据查询搜索文档数量,可以执行以下操作:

 userModel.count({yourQueryGoesHere}, setNumberofDocuments);

setNumberofDocuments is a separeted function :

setNumberofDocuments 是一个单独的函数:

var setNumberofDocuments = function(err, count){ 
        if(err) return handleError(err);

        numberofDocs = count;

      };

Now you can get the number of Documents anywhere with a getFunction:

现在您可以使用 getFunction 在任何地方获取文档数量:

     function getNumberofDocs(){
           return numberofDocs;
        }
 var number = getNumberofDocs();

In addition , you use this asynchronous function inside a synchronous one by using a callback, example:

此外,您可以通过使用回调在同步函数中使用此异步函数,例如:

function calculateNumberOfDoc(someParameter, setNumberofDocuments){

       userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

       setNumberofDocuments(true);


} 

Hope it can help others. :)

希望它可以帮助其他人。:)