0

I need to mention that I'm new to Node.js in general but I'm not sure why for the following code will give me different outputs in console for questions and allQuestions variable ?

var models = require('./models')(mongoose);
var query = models.Question.find({});

var questions = Array();

query.exec(function(err, allQuestions){
  //catch the error;
  questions = allQuestions;
  console.log(allQuestions);

});

console.log(questions);

Output of questions variable will be only: Mongoose: questions.find({}) { fields: undefined } while allQuestions will contain all the questions from database.

I need to know why ?

Also I need that my question variable contains allQuestions from database.

victorkt
  • 13,992
  • 9
  • 52
  • 51
Splendid
  • 1,317
  • 4
  • 20
  • 41

1 Answers1

1

Thats because query.exec() runs the function you passed as parameter asynchronously and the last line console.log(questions); will be executed before the callback is.

If you need the value of questions, then use another callback:

var models = require('./models')(mongoose);
var query = models.Question.find({});

var questions = Array();

query.exec(function(err, allQuestions){
  //catch the error;
  questions = allQuestions;
  console.log(allQuestions);
  done();
});

function done() {
    console.log(questions);
    // handle `questions` here ...
}
victorkt
  • 13,992
  • 9
  • 52
  • 51