Search code examples
javascriptnode.jsmongodbmonk

MongoDB MonkAPI setting a variable based on find result that is available outside the db request


I'm trying to set a variable based on the result of a find through Monk API on MongoDB in a Node JS application (it's my first time of using MongoDB).

This is an example of the code I have;

var variableIWantToSet;
var collection = req.db.get('myCollection');
collection.find( { foo: 'bar' },{
  fields : { myTargetField: 1, _id: 0},
  limit : 1,
  sort : {$natural : -1}
}
, function(err, doc) {
    if (err) {
      console.log(err);
    }
    variableIWantToSet = doc[0].myTargetField;
});
console.log(variableIWantToSet);

If I console.log(doc[0].myTargetField) within the function I get the right value, but the console.log(variableIWantToSet) returns undefined.

Help appreciated. Thanks.


Solution

  • the console.log is outside the callback. so that it's undefined. Put it in the callback.

    var collection = req.db.get('myCollection');
    collection.find( { foo: 'bar' },{
      fields : { myTargetField: 1, _id: 0},
      limit : 1,
      sort : {$natural : -1}
    }
    , function(err, doc) {
        if (err) {
          console.log(err);
        }
        var variableIWantToSet = doc[0].myTargetField;
        console.log(variableIWantToSet);
    });
    

    for making it easier to understand :

     //The callback function will be call after the mongodb response right value.
    var callback = function(err, doc) {
        if (err) {
          console.log(err);
        }
        variableIWantToSet = doc[0].myTargetField;
        console.log(variableIWantToSet); // return doc[0].myTargetField;
    }; 
    
    var variableIWantToSet;
    
    var collection = req.db.get('myCollection');
    collection.find( { foo: 'bar' },{
      fields : { myTargetField: 1, _id: 0},
      limit : 1,
      sort : {$natural : -1}
    }
    , callback);
     console.log(variableIWantToSet); // return undefined;
    

    if you don't understand about callback, google it, it's the basic of asynchronous programming, which makes javascript different.