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

smi*_*exu 86 mongoose mongodb node.js

如何知道数据已保存的模型数?有一种方法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');
Run Code Online (Sandbox Code Playgroud)

userCount是一个对象,哪个方法调用才能得到真实count

谢谢

UpT*_*eek 136

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

这是一个用法示例:

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

  • `count`方法被删除,你可以使用`countDocuments`相同的语法 (9认同)

alm*_*pal 111

以下代码有效.注意使用计数.

 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);
      });
   }
 }); 
Run Code Online (Sandbox Code Playgroud)

  • .count()现在已弃用,请依赖@benjamin答案 (2认同)

小智 23

collection.count已弃用,将在以后的版本中删除.使用集合.countDocuments或集合.estimatedDocumentCount代替.

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

    res.json({ count: count });
});
Run Code Online (Sandbox Code Playgroud)

  • 这是文档链接:https://mongoosejs.com/docs/api.html#model_Model.estimatedDocumentCount (3认同)

Rif*_*een 20

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

userModel.count({name: "sam"});
Run Code Online (Sandbox Code Playgroud)

要么

userModel.count({name: "sam"}).exec(); //if you are using promise
Run Code Online (Sandbox Code Playgroud)

要么

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

  • DeprecationWarning:collection.count 已弃用,您应该使用 .estimatedDocumentCount() 或 .countDocuments() 代替。 (2认同)

hei*_*ala 8

如猫鼬文档和本杰明的答案中所述,不建议使用Model.count()方法。除了使用count()以外,其他方法如下:

Model.countDocuments(filterObject,回调)

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

Model.estimatedDocumentCount()

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

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

1)传递回调函数

例如,使用.countDocuments()对集合中的所有文档进行计数:

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

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

SomeModel.countDocuments({ name: 'Snow' }, function(err, count) {
    //see other example
}
Run Code Online (Sandbox Code Playgroud)

2)使用.then()

猫鼬查询具有.then(),因此它是“ thenable”的。这是为了方便起见,查询本身并不是一个承诺。

例如,使用.estimatedDocumentCount()对集合中的所有文档进行计数:

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

希望这可以帮助!

  • 很棒的答案! (2认同)

Abi*_*bid 6

使用 mongoose.js 你可以计算文档,

  • 数一数
const count = await Schema.countDocuments();
Run Code Online (Sandbox Code Playgroud)
  • 计数特定
const count = await Schema.countDocuments({ key: value });
Run Code Online (Sandbox Code Playgroud)