kirpt
kirpt

Reputation: 845

How can i remove a specified field from a mongoose document?

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

Answers (3)

azwar_akbar
azwar_akbar

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

mrgoos
mrgoos

Reputation: 1316

You can use destructuring and Template literals:

{$unset: {[`cars.${brand}`]: " "}}

Upvotes: 2

tedcurrent
tedcurrent

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

Related Questions