我正在try 使用NodeJS更新MongoDB的值,这是我的代码:
Controller.js
updateProduct: async (req, res) => {
try {
const { params: { id } } = req;
const { body } = req;
if (!body || Object.keys(body).length === 0) {
Response.ERROR(res, new createError.BadRequest());
} else {
let product = await ProductsService.updateP(id, body);
}
if (!product) {
Response.ERROR(res, new createError.NotFound());
} else {
Response.SUCCSESS(res, 201, `Producto actualizado`, product);
}
} catch (error) {
debug(error);
Response.ERROR(res);
}
},
服务
const updateP = async (id, product) => {
const collection = await Database(COLLECTION);
return collection.updateOne({_id: new ObjectId(id)}, { $set: { ...product } })
};
DB
"body": {
"_id": "651cd5d91e3c20bda7cea881",
"name": "shoes",
"price": 359,
"quantity": 10,
}
我收到了这样的错误:
MongoServerError: Performing an update on the path '_id' would modify the immutable field '_id'
个
我调查过了,试着把...product
换成req.params.name
,但还是不行
我想要这样的东西:
"body": {
"_id": "651cd5d91e3c20bda7cea881",
"name": "Coca-cola",
"price": 359,
"quantity": 10,
}