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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With