I wouldnt be surprised if this has been asked before but I have not found a working example.
Basically I have a set of Boolean data inside of an array of objects and I would like to reuse my API routes/logic to update array of objects dynamically
Data Example:
{
"_id": 1,
"posts": [
{ "_id": d323d32, "published": true, "homepage": false, (...moreBooleanData) },
{ "_id": ffwfwfwc, "published": true, "homepage": false, (...moreBooleanData) },
{ "_id": fdscsdad, "published": true, "homepage": false, (...moreBooleanData) }
]
}
Mongoose Query
await Project.findOneAndUpdate(
{ _id: 1 },
{ $set: { "posts.$[el].published": isChecked } },
{
arrayFilters: [{ "el._id": postid }],
new: true
}
)
The problem is in this line "posts.$[el].published": isChecked. Here I have the key published hard coded but I would like to have this key dynamic so I can grab it from the body of my post request
const { DYNAMIC_KEY , isChecked } = req.body
"posts.$[el].$[DYNAMIC_KEY]": isChecked`
I have tried formatting the $set string with backticks, building it outside the query and passing it as 1 variable all without success. Any ideas?