Javascript Mongoose findOneAndUpdate不是在更新文档,而是在创建一个新文档?
我在后台使用Node、Express和MongoDB/Mongoose。我已设置了此Javascript Mongoose findOneAndUpdate不是在更新文档,而是在创建一个新文档?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我在后台使用Node、Express和MongoDB/Mongoose。我已设置了此放置路线: //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 } },
放置路线:
//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
请求响应中,\u id
和审阅者
都已更改。事实上,它已经为另一个用户创建了一个新文档,而不是更新原始文档。如果我登录到PUT
响应中给出的属于\u id
的帐户,它确实显示为该帐户创建了一个新文档,而没有更新其他/原始帐户的文档
为什么会这样?请提供帮助。您需要将条件作为对象提供
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
替换为findbyiandupdate
退房