12

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!" });
  });
});
user2281858
  • 1,957
  • 10
  • 41
  • 82

2 Answers2

10

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

Akrion
  • 18,117
  • 1
  • 34
  • 54
4

_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
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • In this mongoDB tutorial: https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-2. an updateOne query affects the key "_id", so my question is why is that example working and this one not working, is it a driver issue. – Margach Chris Apr 15 '21 at 08:44
  • You can create the `_id` field, but you can't alter it after it's created. @MargachChris in the tutorial they use `$setOnInsert`, which actually does not update the `_id` field but creates it if the document doesn't exists. – emremrah May 14 '22 at 06:27