2012-07-10 135 views
0

我正在写我自己的类来管理在快速框架内的mongodb查询。这个函数为什么不会返回结果?

了该类看起来像

var PostModel = function(){}; 

PostModel.prototype.index = function(db){ 
    db.open(function(err,db){ 
    if(!err){ 

     db.collection('post',function(err,collection){ 

     collection.find().toArray(function(err,posts){ 
      if(!err){ 
      db.close(); 
      return posts; 
      } 
     }); 
     }); 
    } 
    }); 
}; 

当我调用该函数:

// GET /post index action 
app.get('/post',function(req,res){ 

    postModel = new PostModel(); 
    var posts = postModel.index(db); 
    res.json(posts); 

}); 

我不知道为什么好像性能指标没有任何回报。

但是,如果我改变这样

var PostModel = function(){}; 

PostModel.prototype.index = function(db){ 
    db.open(function(err,db){ 
    if(!err){ 

     db.collection('post',function(err,collection){ 

     collection.find().toArray(function(err,posts){ 
      if(!err){ 
      db.close(); 
      console.log(posts); 
      } 
     }); 
     }); 
    } 
    }); 
}; 

注意索引功能的console.log而不是回报。有了这些变化,我可以在终端看到我想要的所有帖子。这是因为该功能应该尽可能地回收所有帖子。

的问题是,它不返回岗位:(

回答

4

您使用异步函数,它们都得到回调,所以你需要使用一个回调太:

var PostModel = function(){}; 

PostModel.prototype.index = function(db, callback){ 
    db.open(function(err,db){ 
    if(!err){ 

     db.collection('post',function(err,collection){ 

     collection.find().toArray(function(err,posts){ 
      if(!err){ 
      db.close(); 
      callback(posts); 
      } 
     }); 
     }); 
    } 
    }); 
}; 
+0

谢谢:)你帮了我很多东西:) – gaggina 2012-07-10 15:37:36

相关问题