gpt4 book ai didi

javascript - 对路径 '_id' 执行更新将修改不可变字段 '_id'

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:11 24 4
gpt4 key购买 nike

我正在尝试更新 mongo 数据库中的字段。但是,我收到了空心错误。

MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

我的代码要更新。

app.put("/api/inventory/:sku", (req, res, next) => {
const inventory = new Inventory({
_id: req.body.id,
sku: req.body.sku,
total_qty: req.body.total_qty,
current_qty: req.body.current_qty
});
Inventory.updateOne({ sku: req.params.sku }, req.body).then(result => {
res.status(200).json({ message: "Update successful!" });
});
});

最佳答案

看来您只需要更新一条 Inventory 记录。您可以简单地执行以下操作:

app.put("/api/inventory/:sku", (req, res, next) => {
return Inventory.updateOne(
{ sku: req.params.sku }, // <-- find stage
{ $set: { // <-- set stage
id: req.body.id, // <-- id not _id
sku: req.body.sku,
total_qty: req.body.total_qty,
current_qty: req.body.current_qty
}
}
).then(result => {
res.status(200).json({ message: "Update successful!" });
});
});

无需创建新的库存等,因为您只需根据sku更新现有库存即可

这里有关于 updateOne 的更多文档

关于javascript - 对路径 '_id' 执行更新将修改不可变字段 '_id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com