how to push value in to object's property dynamically in mongoose? how to push value in to object's property dynamically in mongoose? mongoose mongoose

how to push value in to object's property dynamically in mongoose?


You need to define your path using the dot notation instead of square brackets:

`authencity.${authencityType}`

For instance authenticity.fake

try:

const result = await News.findOneAndUpdate({ name: newsName }, { $push: { `authencity.${authencityType}`: email } }, { new: true });

Also note that in mongoose's findOneAndUpdate version you need to pass new: true parameter in order to return modified document


const newColumn = `authencity.${authencityType}`;const result = await News.findOneAndUpdate({ name: newsName }, { $push: { [newColumn]: email } }, { new: true });

Here, I have created a dynamic string to construct a column name using template literal and then enclosed it with [], so mongo will consider this a column name