Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose findOneAndUpdate不是在更新文档,而是在创建一个新文档?_Javascript_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Javascript Mongoose findOneAndUpdate不是在更新文档,而是在创建一个新文档?

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 } },

我在后台使用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 } }, { 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

退房