Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename path in response for populate

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?

like image 816
Vladimir Djukic Avatar asked Jul 20 '16 14:07

Vladimir Djukic


People also ask

How does populate work mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What does REF do in mongoose?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.


1 Answers

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

like image 91
Puneet Singh Avatar answered Oct 09 '22 04:10

Puneet Singh