Search code examples
node.jsmongodbmongodb-querymongodb-.net-drivernodejs-server

How to update data using _id in node_js and mongodb


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'


Solution

  • 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 }
        );