1

Below is my code

var mongodb = require('mongodb');
var MongodbClient = mongodb.MongoClient;

MongodbClient.connect('mongodb://localhost/test', function(err, db) {
    if(!err){
        console.log("We are connected!!");
    }

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

    contact.update({name: "Fred"}, {$set: {tel:'09088oooxxaa'}}, function(err,r) {
       if(err){
           console.log("Update err");
       }
       else{
           console.log('Update success');
           console.log(r.name);
       }
   });

   contact.find({name: "Fred"}).toArray(function(err, results) {
       console.log(results[0]);
   });
});

I can get the result array by using find() method in the end of this code.

However, I would like to know is any way I can get same results array in update function code by callback?

I tried to worte "console.log(r.name) in update code but show undefined

2 Answers 2

1

You could also do a findAndModify so you don't need to do the find after the update because it returns the updated item too:

var mongodb = require('mongodb');
var MongodbClient = mongodb.MongoClient;

MongodbClient.connect('mongodb://localhost/test', function(err, db) {
    if(!err){
        console.log("We are connected!!");
    }

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

    contact.findAndModify({name: "Fred"}, {$set: {tel:'09088oooxxaa'}}, function(err,r) {
       // r now contains the entire item updated
       if(err){
           console.log("Update err");
       }
       else{
           console.log('Update success');
           console.log(r.name);
       }
   });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.So I can not use "r" in update callback when use update not findAndModify?
Yes you can't use it with an update command because it returns only the number of row updated not the items.
THanks. I though It will return the updated items also.Did you know where I can find these information which is what data it will return?
1

You need to do the find oepration inside the callback to update. The way you do it, your find operation fires prior to update.

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

contact.update({name: "Fred"}, {$set: {tel:'09088oooxxaa'}}, function(err,r) {
   if(err) {
       console.log("Update err");
   }
   else {
       console.log('Update success');
       contact.find({name: "Fred"}).toArray(function(err, results) {
           console.log(results[0]);
       });
   }
});

1 Comment

Yes, it's in the scope of the callback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.