samedi 28 février 2015

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.


Aucun commentaire:

Enregistrer un commentaire