Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 596
pham cuong Avatar asked Apr 29 '16 04:04

pham cuong


1 Answers

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

like image 77
Alpesh Patil Avatar answered Oct 09 '22 17:10

Alpesh Patil