在路径"_id"上执行更新将修改不可变字段"_id" [英] Performing an update on the path '_id' would modify the immutable field '_id'
本文介绍了在路径"_id"上执行更新将修改不可变字段"_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更新mongo数据库中的字段.但是,我得到了空洞错误.
I am trying to UPDATE fields in mongo database. However, I get the hollowing error.
MongoError:对路径"_id"执行更新会修改不变字段"_id"
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!" });
});
});
推荐答案
_id
is auto-generated - for a more in-depth explanation about what it is, see this answer.
您无法创建此字段-它是在创建任何新文档时创建的.您需要使用 id
字段(不带下划线 _
):
You can't create this field - it's created when you create any new document. You need to use the id
field (no leading underscore _
):
const inventory = new Inventory({
id: req.body.id,
sku: req.body.sku,
total_qty: req.body.total_qty,
current_qty: req.body.current_qty
});
这篇关于在路径"_id"上执行更新将修改不可变字段"_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文