Mongoose update replace entirely former document

Tags: , , ,



I’m trying to update my document to remove a few fields I am testing onto further on in the frontend, I removed the fields with this:

delete myObject.myField;

Thus when I look at it before my mongoose findByIdAndUpdate it has indeed none of these fields then I’m trying to update like so:

Journee.findByIdAndUpdate(req.params.id, journee, {new: true, overwrite: true, runValidators: true, context: 'query'}, )
            .then(() => {
                res.status(200).json()
            })
            .catch(err => {
                res.status(400).json({ err })
            })

But when I use the overwrite option like so, it triggers my unique validators and returns an error.

I don’t understand how to achieve my goal, it seems to me that mongo is creating a duplicate document and then suppressing the old one or something like this. Instead of just emptying the document and filling it with new data.

Answer

If I have understand well, you want to remove some fields and update the document with the new one.

So I think a better approach is use $unset. Reference here

With $unset you can delete any field from the document.

An example here

With a query like this:

db.collection.update({
  "id": 1
},
{
  "$unset": {
    "field1": "",
    "field3": ""
  }
})

You can find the document you want (for example using id or whatever you want). And then $unset and delete as fields as you want.

Using mongoose is the same:

var update = await model.updateOne({
  "id": 1
},
{
  "$unset": {
    "field1": "",
    "field3": ""
  }
})
console.log(update)

Show the output:

{ n: 1, nModified: 1, ok: 1 }


Source: stackoverflow