Mongodb Node.js获取插入文档的数量

时间:2016-01-15 19:41:19

标签: javascript node.js mongodb

我希望得到插入记录的计数,而不是重复调用db.collection.count()

我的代码

exports.save = function(json) {
    var url = 'mongodb://localhost/apps';
    MongoClient.connect(url, function(err, db) {
      var collection = db.collection("apps");
      collection.insert(json, {w: 1}, function(err, records){
        console.log("Inserted : "+records.count() );
      });
    });
};

TypeError:无法读取未定义

的属性'count'

1 个答案:

答案 0 :(得分:4)

insert()函数接受一个带有insertWriteOpResult的insertWriteOpCallback。

所以有一个属性insertedCount,它是插入的文档总数。 将.count()替换为.insertedCount

来源:http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#~insertWriteOpResult