mongodb-js / mongoose-autopopulate

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

autopopulate doesn't work with on inherited schemas #15

Closed antonioaltamura closed 8 years ago

antonioaltamura commented 8 years ago

Hi, I'm using a discriminatorKey for inherited schema. The root schema contains

{
...
    tags:[{item:{type: ObjectId, ref: 'tags',autopopulate:true},comment:String}],
...
}

the child schema have a field that refs to the same collection.

{
...
    custom_tags:[{item:{type: ObjectId, ref: 'tags',autopopulate:true},comment:String}],
...
}

The second populate doesn't work

vkarpov15 commented 8 years ago

Can you show your schemas please?

antonioaltamura commented 8 years ago

My schema are huge, but here the part of interest

var rootSchema = mongoose.Schema({
    name:{type:String,required:true},
    type:{type:String},
    tags:[{item:{type: ObjectId, ref: 'tags',autopopulate:true},comment:String}],
    link:{type: String}
}, { timestamps: { createdAt: 'createdAt' }, collection : 'collections', discriminatorKey : '_type' });

var inheritSchema = root.discriminator('inherit', new Schema({
    custom_tags:[{item:{type: ObjectId, ref: 'tags',autopopulate:true},comment:String}],
    facts:{type:String,trim: true },
    reasoning:{type:String,trim: true },
    comments:{type:String,trim: true}
},{discriminatorKey : '_type'}) );
vkarpov15 commented 8 years ago

Make sure you attach the plugin to the child schema:

var inheritSchema = new Schema({
    custom_tags:[{item:{type: ObjectId, ref: 'tags',autopopulate:true},comment:String}],
    facts:{type:String,trim: true },
    reasoning:{type:String,trim: true },
    comments:{type:String,trim: true}
},{discriminatorKey : '_type'});

inheritSchema.plugin(autopopulate);
var Inherit = root.discriminator('inherit', inheritSchema);

Discriminators do not pull plugins from their parent schemas. See https://github.com/Automattic/mongoose/issues/3977.