0

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?

1 Answers1

0

From the MDN docs:

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

This 0 member may be from a different enumerable property up the prototype chain.

Community
  • 1
  • 1
kyrisu
  • 4,541
  • 10
  • 43
  • 66