How to rename a path in response to filling

I have a query like this:

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

The final answer for objectIdwould be:

objectId: {
...
}

How can I change it to userin response without changing the real path?

+4
source share
1 answer

You can do this by virtual populating the 2010 mongoose version. To do this, you need to define a virtual field in the mongoose pattern.

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 a search query, just populate it with the user.

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

The above code is not tested in the program, there may be typos, you can get more detailed information about mongoose virtual filling at the link below

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

0

Source: https://habr.com/ru/post/1648526/


All Articles