Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass an extra parameter to a mongoose update callback

I have mongoose update call and would like to pass an extra parameter...like so:

Trying to pass isLoopOver

UserInfo.update({_id: userInfo._id}, {'value': someval}, function(err, numAffected, isLoopOver ) {
    console.log('IsLoopOver ' + JSON.stringify(isLoopOver) );
    if (isLoopOver){
        doSomething(isLoopOver);
    }
});

Tried the above but I get an object (inside the callback) as below:

{"updatedExisting":true,"n":1,"connectionId":117,"err":null,"ok":1}

No idea why it is showing the status from mongo.

Question: How can I pass an extra parameter thru the callback?

like image 268
Ram Iyer Avatar asked Jun 01 '13 23:06

Ram Iyer


Video Answer


2 Answers

The common way is:

var isLoopOver = false;
UserInfo.update({_id: userInfo._id}, {'value': someval}, function(err, numAffected) {
    console.log('IsLoopOver ' + JSON.stringify(isLoopOver) );
    if (isLoopOver){
        doSomething(isLoopOver);
    }
});

If you are worried about some code will change the value of isLoopOver before the update's callback function being called, using the following code:

(function (isLoopOver) {
  UserInfo.update({_id: userInfo._id}, {'value': someval}, function(err, numAffected) {
      console.log('IsLoopOver ' + JSON.stringify(isLoopOver) );
      if (isLoopOver){
          doSomething(isLoopOver);
      }
  });
}(isLoopOver));

The reason why your isLoopOver variable is showing the status from mongo is that in the callback function, the isLoopOver is a formal parameter instead of a actual parameter.

like image 167
luin Avatar answered Oct 06 '22 18:10

luin


You can use Underscore's partial function:

UserInfo.update(..., _.partial(function( isLoopOver, err, numAffected ) {
}, isLoopOver ))
like image 6
gustavohenke Avatar answered Oct 06 '22 18:10

gustavohenke