mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
222 stars 36 forks source link

Autopopulate in discriminated collections. #26

Closed irisked closed 4 years ago

irisked commented 7 years ago
var baseSchema = new Schema({
       field: String
});
baseSchema.plugin(autopopulate);
module.exports = mongoose.model('BaseSchema', baseSchema);`    

var childSchema = new Schema({
       items: [{
             type: Schema.Types.ObjectId, ref: 'ChildData', autopopulate: true
       }]
});
childSchema.plugin(autopopulate);
module.exports = BaseSchema.discriminator('ChildSchema', childSchema);`

Autopopulate don't work if populated field are in child schema.

UPD. Works correctly if query "based" on child schema. E.g. ChildSchema.find({}), but don't work if BaseSchema.find({})

vkarpov15 commented 7 years ago

Yeah unfortunately this is very difficult to support with the current way mongoose-autopopulate works. It's based entirely on pre('find') and pre('findOne') hooks, which don't get fired for the child model when you do find() on the parent model.

jmikrut commented 4 years ago

This is a must-have for a project I have in the works. Has there been any movement? Any workarounds?

vkarpov15 commented 4 years ago

@jmikrut not yet. You would need to call populate() manually, Base.find().populate('items'), or write your own query middleware.