MongoDB返回" undefined"的node.js

时间:2014-06-21 18:53:22

标签: node.js mongodb express undefined

我正在使用node.js和monogdb作为我当前的项目。我有问题,我试图解决,但没有希望。所以,我需要你的帮助。我有问题将Mongo查询回调的结果传递给main.js中的路由。在mongoDB.js类中,我有这个函数:

DBManagerConnection.prototype.findSubscriber = function(id){
   database.Subscriber.findOne({subscriberId:id}, function(err, subscriber){
      if(err || !subscriberid){ 
        console.log("No Subscriber recoard here");
      }else{
        console.log("Find:");
        console.log(subscriber);
        return subscriber;
      }
   });
 }

此功能的输出是:

Find:
{ _id: 53a597665f8930ed1665c612,
  subscriberId: 'Sub8efc871fc6fc43765b2c9',
  subscriberName: 'Sub1',
  subscriberDevices: [],
  subscriberIndex: [],
  date: Sat Jun 21 2014 10:32:06 GMT-0400 (EDT) }

到目前为止这么好但是当我为main.js调用此函数时,它返回'undefined',如下所示:

var subb = null;
subb = db.findSubscriber('CPNsSub8efc871fc6fc43765b2c9');
setTimeout(function(){console.log(subb)}, 1000);

输出未定义。

有人能帮帮我吗? 感谢

2 个答案:

答案 0 :(得分:2)

您的findSubscriber函数未返回任何内容,因此它被设置为undefined

我会试着让它更清楚:

DBManagerConnection.prototype.findSubscriber = function(id){

  database.Subscriber.findOne({subscriberId:id}, function(err, subscriber){
    if(err || !subscriberid){ 
      console.log("No Subscriber recoard here");
    } else{
      console.log("Find:");
      console.log(subscriber);
      return subscriber;
    }
  });

};

您的return行位于function(err, subscriber){函数内,而不在function(id){函数内。因此,在这种情况下,当您执行return subscriber;时,您将该值返回到.findOne的逻辑中,而不是.findSubscriber的调用网站。

一般来说,你想要完成的是另一个回调:

DBManagerConnection.prototype.findSubscriber = function(id, callback){
  database.Subscriber.findOne({subscriberId:id}, function(err, subscriber){
    if(err || !subscriber){ 
      console.log("No Subscriber record here");

      callback(err, null);
    } else{
      callback(null, subscriber);
    }
  });
};

db.findSubscriber('CPNsSub8efc871fc6fc43765b2c9', function(err, subscriber){
  console.log(err, subscriber);
});

答案 1 :(得分:0)

使用“return”关键字在异步调用中传回值将不起作用。你需要通过回调传回它。这是代码:

DBManagerConnection.prototype.findSubscriber = function(id, callback){
   database.Subscriber.findOne({subscriberId:id}, function(err, subscriber){
     if(err || !subscriberid){ 
       console.log("No Subscriber recoard here");
       callback({message: "Not found"});
     }else{
       console.log("Find:");
       console.log(subscriber);
       callback(null, subscriber);
     }
   });
};


db.findSubscriber('CPNsSub8efc871fc6fc43765b2c9', funciton(err, result) {     
  if (err) {
    console.log(err);
  } else {
    console.log(result);
  }
});