【问题标题】:Mongoose findOneAndUpdate for updating more than one fields in a documentMongoose findOneAndUpdate 用于更新文档中的多个字段
【发布时间】:2020-11-19 20:41:14
【问题描述】:

我正在使用 mongoose 版本 5.9.25,并且我正在使用 postman 进行 API 测试。

我尝试构建 RESTful API,但同时使用 route.put() 和 findOneAndUpdate 方法并使用标题字段查找文档。

我的文档包含两个字段 - 标题和内容,我想同时更新这两个字段。它只更新我的文档的标题,而内容字段甚至没有添加到对象中。

我尝试过直接通过 mongo 控制台使用原生 MongoBD 驱动程序findOneAndUpdate 方法,效果非常好。

我想使用 mongoose 更新具有新标题和内容的对象,但以下代码未提供所需的输出 Before put request-- Notice the object id is same in both images but only the title field is updated after PUT request as shown in image 2

这是我的更新路线:

app.route("/articles/:articleTitle")
  .put(function(req,res){
    Article.findOneAndUpdate(
      {title:req.params.articleTitle},
      {title: req.body.title ,content: req.body.content},
      {overwrite: true},
      function(err,result){
      if(!err){

        res.send(result);
      }
      else{
        res.send(err);

      }
    });
  });

【问题讨论】:

    标签: mongodb mongoose postman


    【解决方案1】:

    你只是有一个语法错误。您需要使用set 运算符,将代码的更新部分从:

    {title: req.body.title ,content: req.body.content}
    

    到这里:

    {$set: {title: req.body.title ,content: req.body.content}},
    

    您还应该使用new 选项而不是overwrite,我认为它仅适用于update 运算符,但不适用于findOneAnd.. 运算符。

    完整:

    app.route("/articles/:articleTitle")
        .put(function(req,res){
            Article.findOneAndUpdate(
                {title:req.params.articleTitle},
                {$set: {title: req.body.title ,content: req.body.content}},
                {new: true},
                function(err,result){
                    if(!err){
    
                        res.send(result);
                    }
                    else{
                        res.send(err);
    
                    }
                });
        });
    

    【讨论】:

    • 如果你想拥有overwrite 的行为,你可以使用findOneAndReplace
    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 2016-10-15
    • 2017-08-13
    • 2019-09-27
    • 2019-10-05
    • 2018-04-19
    • 2020-08-10
    • 2016-04-30
    相关资源
    最近更新 更多