Bk Razor Bk Razor - 1 month ago 9
Node.js Question

How do you receive plain json object from mongoose findOne()

I have a function that finds one object inside my schema database. If I console.log it, it displays correctly. But outside the function when I use it or console log it, It returns a null object. Please help

My function:

var pushQues = function(quesObj){
var query = {AnswerId: 'Texas'};
Question.findOne(query).lean().exec(function(err,docs){
console.log(docs.Ques);
console.log(docs);
quesObj = docs;
});};


Console(Returns Correctly):

Which is the biggest state?
{ _id: 5815366d49fd95ec160728d8,
Ques: 'Which is the best language?',
Answers: [ 'Texas', 'Georgia', 'New york', 'Ohio' ],
AnswerId: 'Texas' }


Trying to retrieve quesObj from outside function:

var quesObj={};
pushQues(quesObj);
console.log('and quesobj here: '+ quesObj);
console.log('question here: '+ quesObj.Ques);


console(Doesnt work):

and quesob here: [object Object]
quesob here: undefined

Answer

It should be the issue of async nature try to pass the callback to get it.

var pushQues = function(quesObj, callback) {
  var query = {
    AnswerId: 'Texas'
  };
  Question.findOne(query).lean().exec(function(err, docs) {
    console.log(docs.Ques);
    console.log(docs);
    callback(null, docs);
  });
};


pushQues(quesObj,function(err,result){
console.log('and quesobj here: '+ result);
console.log('question here: '+ result.Ques);  
});

Update

var async = require('async');
async.waterfall([
  function(callback) {
    var pushQues = function(quesObj, callback) {
      var query = {
        AnswerId: 'Texas'
      };
      Question.findOne(query).lean().exec(function(err, docs) {
        console.log(docs.Ques);
        console.log(docs);
        callback(err, docs);
      });
    };
  }
], function(err, result) {
if(!err){
  console.log(result);
}
});