Mongoose schema multi ref for one object

How to write multi ref for one property of one mongoose circuit, like this (but wrong):

var Schema = mongoose.Schema; var PeopleSchema = new Schema({ peopleType:{ type: Schema.Types.ObjectId, ref: ['A', 'B'] /*or 'A, B'*/ } }) 
+6
source share
2 answers

You should add a string field to your model and save the name of the external model in it, and the property refPath - 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 an object from the corresponding model.

+4
source

In the current version of Mongoose, I still don’t see that multi ref is possible with the syntax as you want. But you can use part of the "Population through Databases" method described here . We just need to move the demographic logic into an explicit version of the 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 that var People = mongoose.model('People', PeopleSchema); People.findById(_id) .then(function(person) { return person.populate({ path: 'peopleType', model: person.modelNameOfThePeopleType }); }) .then(populatedPerson) { //Here peopleType populated } ... 
0
source

Source: https://habr.com/ru/post/980140/


All Articles