Reputation: 137
I have two related models: Recipe
and User
.
When I fetch a recipe and the related user from the database using populate()
, I want the returned user object to have the id
property instead of the _id
property.
const recipe = await Recipe.findOne({ _id }).populate('user', '-password');
When I log the value of the user model, I want to get this:
{
id: 5eea82b11a97e9429ca61778,
name: 'John Doe',
email: 'johndoe@gmail.com'
}
I tried adding the id
property to the user object, it didn't change anything. I still got the _id
property.
recipe.user = { ...recipe.user, id: recipe.user_id };
Upvotes: 0
Views: 2857
Reputation: 1014
noteSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
This is what i use to remove the underscores - You can just transform the document and delete the bits you dont want
Upvotes: 1