I'm coding an app using Node.js and MongooseJS as my middleware for handling database calls.
My problem is that I have some nested schemas and one of them is populated in a wrong way. When I track every step of the population - all of the data is fine, except the devices
array, which is empty. I double checked the database and there is data inside that array, so it should be fine.
I've got Room
schema. Each object of Room
has a field called DeviceGroups
. This field contains some information and one of them is an array called Devices
which stored devices that are assigned to the parent room.
As you can see in the code, I am finding a room based on it's ID that comes in request to the server. Everything is populated fine and data is consistent with the data in the database. Problem is that the devices
array is empty.
Is that some kind of a quirk of MongooseJS, or am I doing something wrong here, that devices
array is returned empty? I checked in the database itself and there is some data inside it, so the data is fine, the bug is somewhere in the pasted code.
The code:
Schemas:
const roomSchema = Schema({
name: {
type: String,
required: [true, 'Room name not provided']
},
deviceGroups: [{
type: Schema.Types.ObjectId,
ref: 'DeviceGroup'
}]
}, { collection: 'rooms' });
const deviceGroupSchema = Schema({
parentRoomId: {
type: Schema.Types.ObjectId,
ref: 'Room'
},
groupType: {
type: String,
enum: ['LIGHTS', 'BLINDS', 'ALARM_SENSORS', 'WEATHER_SENSORS']
},
devices: [
{
type: Schema.Types.ObjectId,
ref: 'LightBulb'
},
{
type: Schema.Types.ObjectId,
ref: 'Blind'
}
]
}, { collection: 'deviceGroups' });
const lightBulbSchema = Schema({
name: String,
isPoweredOn: Boolean,
currentColor: Number
}, { collection: 'lightBulbs' });
const blindSchema = Schema({
name: String,
goingUp: Boolean,
goingDown: Boolean
}, { collection: 'blinds' });
Database call:
Room
.findOne({ _id: req.params.roomId })
.populate({
path: 'deviceGroups',
populate: {
path: 'devices'
}
})
.lean()
.exec(function(err, room) {
if (err) {
res.send(err);
} else {
room.deviceGroups.map(function(currentDeviceGroup, index) {
if (currentDeviceGroup.groupType === "BLINDS") {
var blinds = room.deviceGroups[index].devices.map(function(currentBlind) {
return {
_id: currentBlind._id,
name: currentBlind.name,
goingUp: currentBlind.goingUp,
goingDown: currentBlind.goingDown
}
});
res.send(blinds);
}
});
}
})