简体   繁体   中英

Mongodb Node.js Get count of inserted documents

I want to get the count of inserted records without making a repeated call to db.collection.count() .

My code

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: Cannot read property 'count' of undefined

The insert() function takes an insertWriteOpCallback with an insertWriteOpResult in it.

So there is a property insertedCount which is the total amount of documents inserted. Replace .count() with .insertedCount .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM