简体   繁体   English

如何在 node_js 和 mongodb 中使用 _id 更新数据

[英]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.我尝试使用节点 js 和 mongodb 进行 crud 操作。所有 crud 操作都运行良好,期待更新方法。我试图找到并更新方法,但它显示错误。如何修复它。

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' MongoError:对路径“_id”执行更新将修改不可变字段“_id”

your req.body also contains _id which is immutable field of mongo.您的 req.body 还包含_id ,它是 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({},{}) Jairo 的回答很好,但您可能喜欢使用.findByIdAndUpdate(req.params.id, req.body)而不是.updateOne({},{})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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