1

I tried crud operation using node js and mongodb.all crud operation is working fine expect update method.I tried to find and update method but its showing error.how to fix it.

updated method

db.collection('Ecommerce').updateOne({ _id:new ObjectId(req.params.id)},{ $set: req.body});

I tried to run showing this type error how to solve it.
MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

smith hari
  • 437
  • 1
  • 11
  • 22

2 Answers2

2

your req.body also contains _id which is immutable field of mongo. you need to remove it in your request body

delete req.body._id;
db.collection('Ecommerce')
    .updateOne(
        { _id:new ObjectId(req.params.id) },
        { $set: req.body }
    );
Jairo Malanay
  • 1,327
  • 9
  • 13
0

Jairo's answer is good but you might love to use .findByIdAndUpdate(req.params.id, req.body) instead of .updateOne({},{})