【问题标题】:Why does this function wont return the results?为什么这个函数不会返回结果?
【发布时间】:2012-07-10 23:22:11
【问题描述】:

我正在编写自己的类来管理 express 框架内的 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 而不是return。通过这些更改,我可以在终端中看到我想要的所有帖子。这是因为该函数按应有的方式检索所有帖子。

问题是它不返回帖子:(

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    你正在使用异步函数,它们都得到回调,所以你也需要使用回调:

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

    【讨论】:

    • 谢谢 :) 你帮助我理解了很多东西 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2015-11-15
    相关资源
    最近更新 更多