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'

4
  • Take the _id property out of the req.body object? Commented Apr 26, 2019 at 6:54
  • _id properly means i could not understand.can give some example code Commented Apr 26, 2019 at 6:55
  • this code also used to findone method its working fine and showing data.but update only its showing this type of error Commented Apr 26, 2019 at 6:57
  • That's makes sense, it's only the update that's trying to modify the object. And if you don't know how to remove a property from an object, I'd suggest some research. Commented Apr 26, 2019 at 6:58

2 Answers 2

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 }
    );
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.