REST API PUT – Update Mongo DB Record

Update a record in Mongo DB database using express js code. PUT Request in REST API sample code example.

app.route('/articles/:articleTitle').put(function(req, res){
  Article.replaceOne(
    {title: req.params.articleTitle}, 
    {title: req.body.title, content: req.body.content},
    {overwrite: true},
    function(err){
      if(!err){
        res.send("Successfully updated article.");
      }else{
        res.send("failed");
      }
    }
  );
})

PUT request entirely replaces the record. If the record is having two properties : title, content . If you are trying to update only one record eg; content , then the title gets deleted. So it just entirely replaces the record with the inputs given.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *