2012-07-10 100 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

相關問題