1

I am using Mongoose to interact with Mongodb. I wrote this code hoping to get a document from Mongodb and assign it to a variable, that's my first try and I am a little lost. The problem is that the variable is undefined outside the function passed to findOne;

var MessageSchema = mongoose.Schema({code: String, to: String, body:$
var Message= mongoose.model('Message', MessageSchema);
mongoose.connect('mongodb://localhost/test');

var msg;

Message.findOne({"code": 123}, function(err, message){
     msg = message; 
      console.log(msg); //here the variable is logged successfully;
});

console.log(msg); // here is undefined;

I am not sure what is going on, my guess is that the findOne is executing asynchronously. If that's so how can I use the msg variable with the retrieved document outside of the function passsed to findOne.

notExactlyAHero
  • 353
  • 1
  • 4
  • 14

0 Answers0