我的GET从DB返回一个包含2个简单对象的数组:
[
{
"_id": "60491b5741893d23216d2de3",
"text": "test`",
"score": 19,
"createdAt": "2021-03-10T19:17:43.809Z"
},
{
"_id": "604947c7b3a7ed28c43c05b7",
"text": "HELLO",
"score": 22,
"createdAt": "2021-03-10T22:27:19.739Z"
}
]在Postman中,我正在尝试做一个PUT到/604947c7b3a7ed28c43c05b7来更新这篇文章。在正文中,我发送:
{
"text": "Updated post test",
"score": 100
}我的节点路由看起来像这样:
router.put('/:id', async(req,res) => {
const posts = await loadPostsCollection();
const post = {};
if (req.body.text) post.text = req.body.text;
if (req.body.score) post.score = req.body.score;
await posts.findOneAndUpdate(
{ _id: req.params.id },
{ $set: post },
{ new: true }
);
res.status(200).send();
})我收到了一条成功的消息,但是当我执行GET来查看数组时,该post的值并没有改变。
发布于 2021-03-11 08:32:48
我假设您使用的是原生mongodb节点驱动程序。在mongoose中,除非传递回调函数,否则findOneAndUpdate()实际上不会执行查询。我当然不知道full是怎么回事,但听起来本地驱动的工作方式是一样的。所以你必须像这样重写你的代码:
posts.findOneAndUpdate(
{ _id: req.params.id },
{ $set: post },
{ new: true },
result => {console.log(result)}
);另一种方法是将.then()附加到末尾,因为according to the docs,如果没有传递回调,它将返回promise。所以我会这样做:
await posts.findOneAndUpdate(
{ _id: req.params.id },
{ $set: post },
{ new: true }
).then(r => r);https://stackoverflow.com/questions/66574237
复制相似问题