mongoose schema multi ref for one property mongoose schema multi ref for one property mongoose mongoose

mongoose schema multi ref for one property


You should add string field to your model and store external model name in it, and refPath property - Mongoose Dynamic References

var Schema = mongoose.Schema;var PeopleSchema = new Schema({    externalModelType:{        type: String    },    peopleType:{        type: Schema.Types.ObjectId,        refPath: 'externalModelType'    }})

Now Mongoose will populate peopleType with object from corresponding model.


In the current version of Mongoose i still don't see that multi ref possible with syntax like you want. But you can use part of method "Populating across Databases" described here. We just need to move population logic to explicitly variant of population method:

var PeopleSchema = new Schema({    peopleType:{        //Just ObjectId here, without ref        type: mongoose.Schema.Types.ObjectId, required: true,    },    modelNameOfThePeopleType:{        type: mongoose.Schema.Types.String, required: true    }})//And after thatvar People = mongoose.model('People', PeopleSchema);People.findById(_id)    .then(function(person) {        return person.populate({ path: 'peopleType',            model: person.modelNameOfThePeopleType });    })    .then(populatedPerson) {        //Here peopleType populated    }...