Monday, 22 May 2017

Express JS MongoDB forEach find

I have a big problem. I want to iterate over collection a result set and for each set i want to find one result.

This looks like this:

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

The Problem is that the page will be rendered before the iteration is complete. I tried to use async and promises, but i didn't get it to run.



via Thomas Mueller

No comments:

Post a Comment