Hadzik Hadzik - 1 month ago 14
Javascript Question

MongoDB .findOne scope

I have a problem with var scope.

var max;
ClassModel.findOne({ class: '1a' }, function (err, class1a) {
if (err) return handleError(err);
max = class1a.members;
console.log(max);
});
console.log(max);


Why first log logs proper value, but second logs undefined?

Answer

Second console.log shows undefined because findOne of mongoose is asynchronous. When you show the first console.log, the result has been processed, in the second not.

Mongoose async operations, like .save() and queries, return Promises/A+ conformant promises. This means that you can do things like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec() (if you're using co).

One thing as you can do is to check when it is done, something like..

 var max;
 var query = ClassModel.findOne({ class: '1a' }, function (err, class1a) {
     if (err) return handleError(err);
     return class1a.members;
});

query.then(function(data) {
    console.log(data); // will show class1a.members value
});

Docs