简体   繁体   中英

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'

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's answer is good but you might love to use .findByIdAndUpdate(req.params.id, req.body) instead of .updateOne({},{})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM