mongoose : Could we populate reference object to a alias/virtual property?
Asked Answered
S

1

10

I'm looking for a way to populate to a alias/virtual property using mongoose ?

For now, mongoose's population is add more fields to the reference property (normally is the identity key). I want to keep my original property and populate the reference's data to the other property.

Ex: seem we need more options on schema

profile_id: { type: mongoose.Schema.Types.ObjectId, ref: 'profiles', populateTo: 'profile' }

And the result return should contain two property: profile_id and profile

After searching time, I found this issue on github :( https://github.com/Automattic/mongoose/issues/3225

Smile answered 29/4, 2016 at 4:17 Comment(0)
S
3

Yes. You can populate reference object using a virtual property. All you need to do is define a virtual property on your schema as below:

UserSchema.virtual('profile', {   
    ref: 'Profiles', // the collection/model name
    localField: 'profile_id',
    foreignField: '_id',
    justOne: true, // default is false
});

And then use populate method:

User.find({}).populate({ path: 'profile', select: 'name status' })

This would return below result:

{   // USER
    _id: 'xx...1',
    username: 'alpesh',
    profile_id: 'xx......7',
    profile: {    // POPULATED
        name: 'Admin',
        status: 'Active
    }
}

Please note - If you're using nodejs/express: Use { toJSON: { virtuals: true } } while defining the Schema

Refer - https://mongoosejs.com/docs/populate.html

Slate answered 24/7, 2020 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.