Home > Enterprise >  {overwrite:true} in update query for mongoose statement usage
{overwrite:true} in update query for mongoose statement usage

Time:01-10

Article.updateOne({title:req.params.aticleTitle},{title:req.body.title,content:req.body.content},{overwrite:true},function(err){}). What is the usage of {overwrite:true} ?

I just want to know that what is the utility of the same

CodePudding user response:

The {overwrite: true} option in the updateOne() method specifies that the update operation should replace the existing document with the updated document. In other words, the update operation will overwrite the existing document with the new document, rather than updating specific fields in the existing document.

This option is useful when you want to completely replace the existing document with a new document, rather than just updating some of the fields in the existing document.

Full syntax for the updateOne() method with the {overwrite: true} option:

Article.updateOne(
    {
        title: req.params.articleTitle
    },
    {
        title: req.body.title,
        content: req.body.content
    },
    { overwrite: true },
    function(err) { /* Perform any necessary actions here */ }
);

CodePudding user response:

If we have this article Article { title, content, image }

Overwrite will replace document with update object:

Article.updateOne({ title }, { title: newTitle, content: newContent }, { overwrite: true })
// Will remove image: Article { newTitle, newContent } 

Without overwriting, only properties in update object will be modified

Article.updateOne({ title }, { title, content })
// Will not remove image: Article { newTitle, newContent, image } 
  • Related