从mongo

时间:2016-10-30 12:05:17

标签: javascript node.js mongodb mongoose

我有一个函数可以在schema数据库中找到一个对象。如果我console.log它,它会正确显示。但是当我使用它或控制台记录它之外的函数,它返回一个空对象。请帮忙

我的功能:

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;
});};

控制台(正确返回):

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

尝试从外部函数中检索quesObj:

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

控制台(无效):

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

3 个答案:

答案 0 :(得分:1)

我假设你想要这个 pushQues函数声明,因为它是异步的问题

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

调用 pushQues功能

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

答案 1 :(得分:1)

应该是异步性质的问题尝试通过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(null, docs);
  });
};


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

<强>更新

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);
}
});

答案 2 :(得分:1)

问题是您正在替换对象引用。你可以这样:

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

功能:

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

另一种选择是使用回调:

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



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