node.js - 为什么这个函数不返回结果?

标签 node.js mongodb express

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

问题是它不返回帖子:(

最佳答案

您正在使用异步函数,它们都会获得回调,因此您也需要使用回调:

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

关于node.js - 为什么这个函数不返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11416540/

相关文章:

node.js - 获取用户 ID 后,Firebase 函数 onCreate 方法无法在 Firestore 上运行

python - 将图像存储在 MongoDB 中

java - 从 MongoDB 整理中获取不需要的输出

python - pymongo 中的 collection.getIndexes() shell 命令的等价物是什么?

node.js - 项目没有从数据库中删除,该项目应该是 :item in the app. 删除 ('/todo/:item' ) int 下面的代码

node.js - dialogflow-fulfillment-library 和express,需要什么?

javascript - 解析短连字符?

node.js - 部署到 Heroku 时已弃用 Meteor Fibers

html - 服务器或 HTML 不显示 CSS(但在打开 HTML 文件时有效)

javascript - Node.js winston 日志记录使用邮件传输仅将 uncaughtException 作为电子邮件发送