How to rename path in response for populate

社会主义新天地 提交于 2021-02-04 23:57:33

问题


I have a query like this:

galleryModel.find({_id: galleryId})
            .populate({
                model: 'User',
                path: 'objectId',
                select: 'firstName lastName'
            })

End response for objectId will be like this:

objectId: {
...
}

How can I change it to user in response without changing real path?


回答1:


You can do this by virtual populate, introduced in mongoose version 4.5 . For that you need to define a virtual field in mongoose schema.

var GallerySchema = new mongoose.Schema({
    name: String,
    objectId: {
        type: mongoose.Schema.Types.ObjectId
    },
});

GallerySchema.virtual('user', {
    ref: 'User',
    localField: 'objectId', 
    foreignField: '_id' 
});

Ans when you run find query, just populate it with user.

Gallry.find({_id: galleryId}).populate('user','firstName lastName').exec(function(error, gallery) {
    console.log(error);
    console.log(gallery);;
});

Above code is not tested in program, there may be typos, You can get more details about mongoose virtual populate on below link

http://mongoosejs.com/docs/populate.html



来源:https://stackoverflow.com/questions/38484504/how-to-rename-path-in-response-for-populate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!