Reputation: 845
I would like to remove dynamically a field from a mongoose document.
What I have tried: I am using
$unset
and when I type the value
"cars.BMW"
it works. But when I want to pass a parameter, which will be a car brand and then to unset it. I tried
{$unset: {"cars."+brand: " "}}
but the plus sign is unexpected.
Upvotes: 0
Views: 5018
Reputation: 1651
You can use $unset to remove feld, here is the example:
User.findOneAndUpdate(
{confirmationKey: req.params.key},
{isConfirmed: true, $unset: { confirmationKey: ""}}, {}, (err, doc) => {
if (err) {
res.status(HttpStatus.BAD_REQUEST).send(StatusGen.getError(err))
} else {
console.log('user = ' + JSON.stringify(doc))
res.send(StatusGen.getSuccess('confirmed'))
}
})
Now field confirmationKey is is deleted.
Upvotes: 0
Reputation: 1316
You can use destructuring and Template literals:
{$unset: {[`cars.${brand}`]: " "}}
Upvotes: 2
Reputation: 431
Dot notation doesn't work like that. In js, you would use bracket notation to create a property dynamically from a string.
exports.deleteBrand = function(req, res){
var brand = req.params.brand;
var query = {};
query["cars." + brand] = "";
Text.update(
{key: req.params.key},
{$unset: query},
function(err){ if(err) res.send(err);
res.json({message: "Car deleted!"});
});
}
The query variable here translates to: {"cars.bmw": ""}
if the brand is "bmw".
EDIT: Edited to match the method by op.
Upvotes: 1