Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose schema multi ref for one property

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

var Schema = mongoose.Schema;
var PeopleSchema = new Schema({
    peopleType:{
        type: Schema.Types.ObjectId,
        ref: ['A', 'B'] /*or 'A, B'*/
    }
})
like image 995
幻影枫韵 Avatar asked Dec 25 '14 05:12

幻影枫韵


2 Answers

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.

like image 158
vasylOk Avatar answered Nov 15 '22 05:11

vasylOk


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 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
    }
...
like image 5
BigBadAlien Avatar answered Nov 15 '22 07:11

BigBadAlien