【问题标题】:Put Method In Express Giving Empty Array将方法放入 Express 给空数组
【发布时间】:2021-04-18 16:24:14
【问题描述】:

**SO 当我创建一个简单的 REST API 并且我正在使用 res.route 并在其中我正在执行一个 get 请求和一个 put 请求但是当我触发 put 请求时它什么也不做,POSTMAN 只是给出一个空字符串我使用 mongodb 作为数据库和 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);
        }
      }
    );
  }  
);

【问题讨论】:

  • 如果您在英语句子中使用标点符号会有所帮助。为什么让人们更难理解您的问题?
  • 感谢您的建议,我会努力改进它,因为英语不是我的第一语言,请您看看问题并尝试帮助我,这将意味着很多
  • 请在您的问题中计算逗号和句号,然后在您的评论中再次计算。老实说,我不认为你在努力。至少句号的概念应该存在于几乎所有语言中。在巴基斯坦,例如,英语和乌尔都语都有。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您正在使用 {overwrite: true}, 并且 MongoDB 服务器不允许使用 updateOne FYI 覆盖文档。所以,从文档中,如果你使用overwrite: true,你应该使用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);
                    }
                }
            );
        }

update() 相同,除了MongoDB 将现有文档替换为给定文档(no atomic operators like $set)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2019-11-23
    • 2016-05-29
    • 2013-12-15
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多