I have the following code:
app.get('/api/getSubRooms/:id', function(req, res, next) {
var rooms = [];
Room.findById(req.params.id, function(err, room) {
if (err) throw err;
var rootRoom = room;
console.log("Subrooms: " + rootRoom.subrooms);
for (var subroom in rootRoom.subrooms) {
Room.findById(subroom, function(err, room) {
if (err) throw err;
rooms.push(room);
if (rooms.length === rootRoom.subrooms.length) res.send(rooms);
});
}
});
});
Now the array rootRoom.subrooms contains ObjectID's from MongoDB, but the for-in loop gives me 0 as the first member, although this member obviously doesn't exist in the array, as the console.log shows. When I use traditional for loop:
for (var i=0; i<rootRoom.subrooms.length; ++i) {
Room.findById(rootRoom.subrooms[i], function(err, room) {
if (err) throw err;
rooms.push(room);
if (rooms.length === rootRoom.subrooms.length) res.send(rooms);
});
everything works as expected. Anyone has an idea why this happens?