Mongoose schema inheritance and model populate
You are looking for a Boss, not a Person:
Boss.findOne({ name: 'Billy'}).populate('bossStatus').exec(callback);
Looks like a bug. With debugging active, this is what's being shown for the population query:
Mongoose: people.findOne({ name: 'Billy' }) { fields: undefined }Mongoose: people.find({ _id: { '$in': [ ObjectId("52a221ee639cc03d71000001") ] } }) { fields: undefined }
(the ObjectId
shown is the one stored in bossStatus
)
So Mongoose is querying the wrong collection (people
instead of bossstatuses
).
As @regretoverflow pointed out, if you're looking for a boss, use the Boss
model and not the Person
model.
If you do want to populate bossStatus
through the Person
model, you can explicitly state a model that needs to be searched for population:
.populate({ path : 'bossStatus', model : 'BossStatus'})// or shorter but less clear:// .populate('bossStatus', {}, 'BossStatus')
EDIT: (with your Device
examples)
driver
is part of LocalDeviceSchema
, but you're querying the Device
model, which has no notion of what driver
is and populating driver
within the context of a Device
instance doesn't make sense to Mongoose.
Another possibility for populating each instance is to do it after you retrieved the document. You already have the deviceCallback
function, and this will probably work:
var deviceCallback = function(err, device) { if(err) { console.log(err); } switch(device.__t) { // or `device.constructor.modelName` case 'LocalDevice': device.populate('driver', ...); break; case 'RemoteDevice': device.populate('networkAddress', ...); break; }};
The reason is that the document is already cast into the correct model there, something that apparently doesn't happen when you chain populate
with the find
.