如何使用 express 和猫鼬将整个数组替换为另一个数组?
示例数据:
{
"_id": 1,
"item": "Car",
"features": [
{
"_id": "1",
"wheels": true
},
{
"_id": "2",
"mirrors": true
}
]
}
假设我将我的功能数组重新排序为:
"features": [
{
"_id": "2",
"mirrors": true
},
{
"_id": "1",
"wheels": true
}
]
我所做的是:
router.patch('/items/:item_id', auth, async (req, res) => {
try {
const item = await Item.update(
{ _id: req.params.item_id },
{ $set: { features: [req.body] } }
)
res.send(item)
} catch (e) {
res.status(400).send(e)
}
})
req.body 是:
[
{
"_id": "2",
"mirrors": true
},
{
"_id": "1",
"wheels": true
}
]
我使用 req.body 传递整个数组以覆盖旧数组,但没有返回我期望的内容
从文档中:
返回: «查询»
更新数据库中的一个文档,而不更新 归还它。
因此Model.update(...)
不会直接返回更新的文档。
如果需要检索更新的文档,则应使用findOneAndUpdate
以及选项{new:true}
:
router.patch('/items/:item_id', auth, async(req, res) => {
try {
const updatedDoc = await Item.findOneAndUpdate({ _id: req.params.item_id },
{ $set: { features: req.body} },
{ new: true }
);
res.send(updatedDoc)
} catch (e) {
res.status(400).send(e)
}
})