2017-05-22 78 views
0

我有个大问题。 我想遍历集合的结果集和每个集合我想找到一个结果。Express JS MongoDB for each找到

这看起来是这样的:

router.get('/', function(req, res) { 
    var floors = []; 
    var rooms = []; 

    req.db.collection('floors').find().sort({_id: 1}).forEach(function(floor) { 
     floors.push(floor); 
    }); 

    req.db.collection('rooms').find().sort({_id: 1}).forEach(function(room) { 
     req.db.collection('floors').findOne({_id: new ObjectID(room.floorId)}, function(error, floor) { 
      room.floor = floor; 
      rooms.push(room); 
     }); 
    }); 

    res.render('rooms', { floors: floors, rooms: rooms }); 
}); 

的问题是,之前迭代完成的页面将被渲染。 我试图使用异步和承诺,但我没有得到它运行。

+1

它因为res.render('房间...在回调之外,在两者之间向上移动}); – FluffyNights

+0

这是行不通的,因为然后渲染将被称为多次(对于每个' –

+0

你使用哪种mongo驱动程序? –

回答

0

基本上,您必须等到发送渲染结果之前完成所有查询。不幸的是,你不使用承诺,所以这会有点混乱。

看来,您正在使用的原生客户端,并根据文档有第二个回调要注意的是这个请求会得到相当重的,当所有的迭代完成 http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#forEach

router.get('/', function(req, res, next) { 
    var floors = []; 
    var rooms = []; 

    function done(err){ 
    if(err) { 
     return next(err); 
    } 
    res.render('rooms', { floors: floors, rooms: rooms }); 
    } 

    function getRooms(err){ 
    if(err){ 
     return next(err); 
    } 
    req.db.collection('rooms').find().sort({_id: 1}).forEach(function(room) { 
     // you already have all the floors, no need to hit the db again 
     floors.find(floor => floor._id === room.floorId); // not sure about this 100% as _id could be an object 
    }, done); 
    } 

    req.db.collection('floors').find().sort({_id: 1}).forEach(function(floor) { 
    floors.push(floor); 
    }, getRooms); 

}); 

被调用当你的数据库增长。