【发布时间】: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 请求响应中,_id 和reviewer 都发生了变化。实际上,它为另一个用户创建了一个新文档,而不是更新原始文档。如果我登录到 PUT 响应中给出的属于 _id 的帐户,它确实表明为该帐户创建了一个新文档,并且没有更新其他/原始帐户的文档。
为什么会这样?请帮忙。
【问题讨论】:
标签: javascript node.js mongodb express mongoose