【问题标题】:How to get all count of mongoose model?如何获得猫鼬模型的所有计数?
【发布时间】:2012-06-04 10:17:12
【问题描述】:

我如何知道已保存数据的模型的数量?有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');

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

谢谢

【问题讨论】:

  • 如果您使用的是 ES 2016,您可以将 count 调用包装在 promise 中并使用生成器调用它。

标签: node.js mongodb mongoose


【解决方案1】:

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

这是一个使用示例:

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

【讨论】:

  • 举个例子获取count同步方式的方法
  • 对我来说也一样。我正在寻找相同的
  • count 方法已被废弃,您可以使用 countDocuments 相同的语法
  • @KirNovak 谢谢兄弟。我还在猫鼬中为deprecation 提供了网址。
【解决方案2】:

下面的代码有效。注意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);
      });
   }
 }); 

【讨论】:

    【解决方案3】:

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

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

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

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

    对于旧版本的猫鼬,请使用

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

    【讨论】:

    • DeprecationWarning:collection.count 已被弃用,您应该改用 .estimatedDocumentCount() 或 .countDocuments()。
    • countDocuments 根据来自猫鼬的文档是正确的;),谢谢
    【解决方案4】:

    collection.count 已弃用,将在未来版本中删除。请改用 collection.countDocuments 或 collection.estimatedDocumentCount

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

    【讨论】:

    • 我遇到的问题是,在我们的项目中,设置例行程序会测试任何集合中的现有项目。 count() 方法的行为很奇怪:当集合不为空时,它有时什么也不返回(未定义、空、零或假——我们无法进一步调查)。我们仍然没有找出导致问题的原因,因为这是一种很少发生的竞争条件。使用 countDocuments({}) 现在对我们有用。谢谢!
    • UnhandledPromiseRejectionWarning: TypeError: userModel.countDocuments is not a function 在我自己的 userModel 上使用时出现错误?
    • 我们如何将“userModel.countDocuments”作为同步调用,以便我可以向架构中添加一个虚拟,从而在我的文档中添加一些“键和值”。
    【解决方案5】:

    解决方案的背景

    正如猫鼬文档和本杰明的回答中所述,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 学习,

    【讨论】:

    • 真棒答案!
    【解决方案6】:

    使用 mongoose.js 可以统计文档,

    • 全部统计
    const count = await Schema.countDocuments();
    
    • 具体计数
    const count = await Schema.countDocuments({ key: value });
    

    【讨论】:

      【解决方案7】:

      这里投票最高的答案非常好我只是想加起来 await 的使用,以便可以实现所要求的功能:

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

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

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

      【讨论】:

        【解决方案8】:

        Model.count() 方法在 mongoose 版本 6.2.0 中已弃用。如果您想计算集合中的文档数量,例如count({}),请改用 estimatedDocumentCount() 函数。否则,请改用countDocuments() 函数。

        Model.estimatedDocumentCount() 估计 MongoDB 集合中的文档数。对于大型集合,它比使用 countDocuments() 更快,因为estimatedDocumentCount() 使用集合元数据而不是扫描整个集合。

        例子:

        const numAdventures = await Adventure.estimatedDocumentCount();
        

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

        【讨论】:

          【解决方案9】:

          如前所述,您的代码将无法正常工作。解决方案是使用回调函数,但如果您认为它会将您带入“回调地狱”,您可以搜索“Promises”。

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

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

          如果你想根据查询搜索文档的数量,你可以这样做:

           userModel.count({yourQueryGoesHere}, setNumberofDocuments);
          

          setNumberofDocuments 是一个单独的函数:

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

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

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

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

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

          【讨论】:

          • 在函数 calculateNumberOfDoc() 中,为什么要调用 setNumberofDocuments(true) ?即使在实际计数返回之前,它不会首先导致错误吗??
          猜你喜欢
          • 2014-12-09
          • 2021-02-02
          • 1970-01-01
          • 2014-03-06
          • 2021-06-19
          • 1970-01-01
          • 1970-01-01
          • 2020-09-26
          • 2012-12-27
          相关资源
          最近更新 更多