Search code examples
mongoosemongoose-schemamongoose-populate

Mongoose virtual population when foreignField is an object in the model


I am trying to populate a virtual property with mongoose, which in my model is an object. I don't know how to target the foreignField. I couldn't find any example, I'd appreciate any help :)

Favour model:

owner: {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        },
        status: {
            type: String,
            default: null // In progress, Completed
        }
    },

User model where the virtual field is:

userSchema.virtual('favours', {
    ref: 'Favour',
    localField: '_id',
    foreignField: ?????
})

Solution

  • SOLVED!!

    userSchema.virtual('favours', {
        ref: 'Favour',
        localField: '_id',
        foreignField: 'owner.user'
    })