I am trying to UPDATE fields in mongo database. However, I get the hollowing error.
MongoError: Performing an update on the path '_id' would modify the immutable field '_id'
My Code to update.
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!" });
});
});
It seems you only need to update one Inventory
record. You can simply do this:
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!" });
});
});
There is no need to create new Inventory
etc since all you need is to update an existing one based on sku
Here is more documentation on updateOne
_id
is auto-generated - for a more in-depth explanation about what it is, see this answer.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With