Mongoose variable schema reference

628 views Asked by At

I'm looking for the best way to have a parent model that references variable child models. Is there a way to set the reference upon saving the parent model, then have it populate the child automatically? If not, what is the best way of achieving a parent model that has variable sub-fields.

var ChildSchema1 = new Schema({
    field1: String,
    field2: String
});


var ChildSchema2 = new Schema ({
    field3: Number,
    field4: String
});

var ParentSchema = new Schema({
    name: {type: String, required: true},
    child_ref: {type: ObjectId, ref: ChildSchema1 OR ChildSchema2}
});
1

There are 1 answers

0
hemelamed On BEST ANSWER

I had a similar problem, where I needed to do schema inheritance. It seems like this github project will work for us both:

https://github.com/briankircho/mongoose-schema-extend