【问题标题】:Mongoose findOneAndUpdate is not updating the document, instead it is creating a new one?Mongoose findOneAndUpdate 不更新文档,而是创建一个新文档?
【发布时间】:2019-10-05 22:45:03
【问题描述】:

我在后端使用 Node、Express 和 MongoDB/Mongoose。我设置了这个PUT 路由:

//where id is the unique id of the review, not the movie
router.put('/update/:id', [jsonParser, jwtAuth], (req, res) => {
    Review.findOneAndUpdate(req.params.id,
        { $set: { ...req.body } }, { new: true })
        .then(review => {
            console.log(review);
            res.status(203).json(review);
        })
        .catch(err => res.status(500).json({message: err}));
});

在我的POST 路由上创建新文档时使用 Postman,响应如下:

{
    "genre_ids": [
        "28"
    ],
    "_id": "5ce112d0aeadc44ea0ea7bb0",
    "movieId": 447404,
    "title": "Pokemon Detective Pikachu",
    "poster_path": "/wgQ7APnFpf1TuviKHXeEe3KnsTV.jpg",
    "reviewer": "5cda5d08f3a74252c83b4a63",
    "reviewTitle": "the best",
    "reviewText": "new review",
    "reviewScore": 5,
    "__v": 0
}

当我尝试更新此 url 上的以下文档时使用 Postman .../review/update/5ce112d0aeadc44ea0ea7bb0 其中 id 取自上面 POST 响应的 _id。 我在PUT 请求中做了一个非常简单的更改,只是为了更改分数。

{
    "reviewScore": 1
}

然后我从PUT 路由得到以下响应。

{
    "genre_ids": [
        "28"
    ],
    "_id": "5ce089116b537a08403ed25f",
    "movieId": 447404,
    "title": "Pokemon Detective Pikachu",
    "poster_path": "/wgQ7APnFpf1TuviKHXeEe3KnsTV.jpg",
    "reviewer": "5ce0882d90b63613700b066a",
    "reviewTitle": "the best",
    "reviewText": "updated review",
    "reviewScore": 1,
    "__v": 0
}

您可以看到在PUT 请求响应中,_idreviewer 都发生了变化。实际上,它为另一个用户创建了一个新文档,而不是更新原始文档。如果我登录到 PUT 响应中给出的属于 _id 的帐户,它确实表明为该帐户创建了一个新文档,并且没有更新其他/原始帐户的文档。

为什么会这样?请帮忙。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您需要以对象的形式提供条件。

    router.put('/update/:id', 
        [jsonParser, jwtAuth], 
        (req, res) =>{
             Review.findOneAndUpdate({'_id' :req.params.id}, { $set: { ...req.body } }, { new: true })
            .then(review => { console.log(review);
             res.status(203).json(review); 
            })
            .catch(err => res.status(500).json({message: err}));
        }
    );
    

    或者,如果您想在代码中直接使用id,只需将findOneAndUpdate 替换为findByIdAndUpdate

    查看Mongoose Query API

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2017-08-13
      • 2016-10-15
      • 1970-01-01
      • 2021-09-12
      • 2020-08-10
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多