Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing an update on the path '_id' would modify the immutable field '_id' [duplicate]

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!" });
  });
});
like image 292
user2281858 Avatar asked May 28 '19 21:05

user2281858


2 Answers

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

like image 119
Akrion Avatar answered Sep 21 '22 00:09

Akrion


_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
});
like image 32
Jack Bashford Avatar answered Sep 21 '22 00:09

Jack Bashford