0

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?

Hadzik
  • 13
  • 5

1 Answers1

1

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

BrTkCa
  • 4,703
  • 3
  • 24
  • 45