Reputation: 568
I have an array in mongo document as below.
{
company: [
{name: "exist"},
{name: "cool"},
{name: "ho"}
]
}
And I want to get rid of a data in the array with position value.
So I made a query.
await Company.findOneAndUpdate({
_id: "xdef"
},
{
$unset: {
'company.1': 1
}
}
})
It works very well. And now,I want to put position by query.
await Company.findOneAndUpdate({
_id: "xdef"
},
{
$unset: {
`company.{req.query.position}`: 1
}
}
})
But it gives me an error. How can I make a code for this situation adequately?
Thank you so much for reading it.
Upvotes: 0
Views: 26
Reputation: 3334
You can use the computed property names. And you are missing $
also in the string literal.
await Company.findOneAndUpdate({
_id: "xdef"
}, {
$unset: {
[`company.${req.query.position}`]: 1
}
}
})
With Computed Property Names you can use an expression that will be computed as a property name on an object.
Upvotes: 1