简体   繁体   中英

iterate over Result returned from mongodb in nodejs

I could not able to iterate through Result returned from mongodb

Here is code that connect to mongodb and gets the result

MongoClient.connect(url, function (err, db) {       

        var collection = db.collection('users');            

            collection.remove({}, { w: 1 }, function (err, result) {
                    console.log(result.ok);
                    res.json    ({ success: true, obj:result.ok});                    
            })
});

the result is

obj: {ok: 1,n: 0}

I am getting undefined when i tried to access the value of n using result.n .

Could anyone let me know the way to access the values of returned result in nodejs

Thanks

No it isn't. The result of:

res.json({ "success": true, "obj": result })

is

{ "success": true, "obj": { "ok": 1, "n": 0 } }

and not what you claim as that is how the object serializes to JSON and how you are accessing it.

However the "true" object returned has itself it's own result key, so if you want to access the n property or even the ok property then you instead must do this:

console.log(result.result.n);

And here is the simple listing that proves this:

var async = require('async'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient;

MongoClient.connect("mongodb://localhost/test",function(err,db) {

  var collection = db.collection('testme');

  async.series(
    [
      function(callback) {
        collection.remove({},callback);
      },
      function(callback) {
        collection.insert(
          [
            { "data": 1 },
            { "data": 2 }
          ],
          callback
        );
      },
      function(callback) {
        collection.remove({},function(err,result) {
          console.log(JSON.stringify(result));
          console.log(JSON.stringify(result.result.n));
          callback(err);
        });
      }
    ],
    function(err) {
      db.close();
    }
  );

});

With expected results:

{"ok":1,"n":2}
2

This is because what is "actually" returned is a deleteWriteOpResult object from the node native driver API and not a plain object. The accessor method is really what you need.

The .remove() method is also considered deprecated in the API and the preference is to use .deleteMany() instead. They both in fact do the same thing, but the deprecation notice means your code should be using that method for future compatibility:

var async = require('async'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient;

MongoClient.connect("mongodb://localhost/test",function(err,db) {

  var collection = db.collection('testme');

  async.series(
    [
      function(callback) {
        collection.deleteMany({},callback);
      },
      function(callback) {
        collection.insert(
          [
            { "data": 1 },
            { "data": 2 }
          ],
          callback
        );
      },
      function(callback) {
        collection.deleteMany({},function(err,result) {
          console.log(JSON.stringify(result));
          console.log(JSON.stringify(result.result.n));
          callback(err);
        });
      }
    ],
    function(err) {
      db.close();
    }
  );

});

According to mongodb's docs - db.collection.remove()

.remove should returns a WriteResult object that looks like WriteResult({ "nRemoved" : 1 }) . In case of error, it should return:

WriteResult({
   "nRemoved" : 21,
   "writeConcernError" : {
      "code" : 64,
      "errInfo" : {
         "wtimeout" : true
      },
      "errmsg" : "waiting for replication timed out"
   }
})

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