Although this question may have come up before, I haven't been able to find a solution that works.
Essentially, I have an array of objects containing Boolean data and I want to be able to update these objects dynamically using my API routes/logic.
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 issue lies in the line
"posts.$[el].published": isChecked
. Instead of hardcoding the key published
, I want it to be dynamic so that I can retrieve it from the body of my post request.
const { DYNAMIC_KEY , isChecked } = req.body
"posts.$[el].$[DYNAMIC_KEY]": isChecked`
I've attempted various methods such as using backticks for the $set
string and building it outside the query, but none have been successful. Any suggestions?