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

Viewed 698

I want to push the value into array based on the property value recieved from frontend using mongoose.

Schema:

authencity: {
        fake: [],
        notSure: [],
        authentic: [],
      }

Now I want to push the value into array based on property value received from frontend

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

authencityType could be anything like fake, notSure, authentic based on this value I want to insert the value into respective array.

Sample Data:

Sample Document :{
    "_id": {
        "$oid": "5f0af1e09a724b06c86bfaec"
    },
    "authencity": {
        "fake": [],
        "notSure": [],
        "authentic": []
    },
    "name": "Rajasthan deputy CM Sachin Pilot\u2019s supporters come to Gurugram resort, call police summon a joke",
    "description": "",
    "url": "https://news.google.com/__i/rss/rd/articles/CBMiqwFodHRwczovL3d3dy5oaW5kdXN0YW50aW1lcy5jb20vaW5kaWEtbmV3cy9yYWphc3RoYW4tZGVwdXR5LWNtLXNhY2hpbi1waWxvdC1zLXN1cHBvcnRlcnMtY29tZS10by1ndXJ1Z3JhbS1yZXNvcnQtY2FsbC1wb2xpY2Utc3VtbW9uLWEtam9rZS9zdG9yeS1ZQ1BQVDFlandtb1RoQXJaRXVabmNOLmh0bWzSAa0BaHR0cHM6Ly9tLmhpbmR1c3RhbnRpbWVzLmNvbS9pbmRpYS1uZXdzL3JhamFzdGhhbi1kZXB1dHktY20tc2FjaGluLXBpbG90LXMtc3VwcG9ydGVycy1jb21lLXRvLWd1cnVncmFtLXJlc29ydC1jYWxsLXBvbGljZS1zdW1tb24tYS1qb2tlL3N0b3J5LVlDUFBUMWVqd21vVGhBclpFdVpuY05fYW1wLmh0bWw?oc=5",
    "category": "general",
    "language": "en",
    "country": "in",
    "__v": 0
}

Received Data : email : abcd@gmail.com authencityType could be fake or notSure or authentic

I want to push value in specific array based on authencityType recieved

2 Answers

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

Related