幻影枫韵
幻影枫韵

Reputation: 251

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'*/
    }
})

Upvotes: 25

Views: 15303

Answers (3)

Kiisi Felix
Kiisi Felix

Reputation: 13

You can achieve this using Dynamic References via refPath

const commentSchema = new Schema({
body: { type: String, required: true },
doc: {
    type: Schema.Types.ObjectId,
    required: true,
    // Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
    // will look at the `docModel` property to find the right model.
    refPath: 'docModel'
},
docModel: {
    type: String,
    required: true,
    enum: ['BlogPost', 'Product']
}

});

Gotten from mongoose docs, Link to mongoose docs for dynamic references via refPath

Upvotes: 0

vasylOk
vasylOk

Reputation: 566

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.

Upvotes: 41

BigBadAlien
BigBadAlien

Reputation: 256

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
    }
...

Upvotes: 6

Related Questions