[Fixed] Put Method In Express Giving Empty Array

Issue

**SO when I am creating a simple REST API and I am using res.route and in it I am doing a get request and a put request but when i trigger put request it does not do anything and POSTMAN just give a empty string i am using mongodb as database and mongoose enter code here **

app.route("/articles/:ReqTitle")
  .get(function(req, res){
    const RequestedArtical = req.params.ReqTitle;
    Article.findOne({title: RequestedArtical}, function(err, FoundArticle){
      if(FoundArticle){
        res.send(FoundArticle);
      }else{
        res.send("No artice with that title was found");
      }
    });
  }
).put(function(req, res){
    const RequestedArtical = req.params.ReqTitle;
    Article.updateOne({title: RequestedArtical},
      {title: req.body.title, content: req.body.content},                              
      {overwrite: true},
      function(err){
        if(!err){
          res.send("Sucessfulyy updated the article");                                           
        }else{
          res.send(err);
        }
      }
    );
  }  
);

Solution

You are using {overwrite: true}, and The MongoDB server disallows overwriting documents using updateOne FYI. So, from the Documentation, if you use overwrite: true, you should use replaceOne()

put(function(req, res) {
            const RequestedArtical = req.params.ReqTitle;
            console.log(RequestedArtical);
            Article.replaceOne({
                    title: RequestedArtical
                }, {
                    title: req.body.title,
                    content: req.body.content
                },
                //{overwrite: true},
                                
                function(err) {
                    if (!err) {
                        res.send("Sucessfulyy updated the article");
                    } else {
                        res.send(err);
                    }
                }
            );
        }

Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set).

Leave a Reply

(*) Required, Your email will not be published