在NodeJS上考虑以下代码以按ID更新文档:
router.put('/:orderId', async(req, res) => {
let update_orderId = req.params.orderId;
let new_item = req.body.item;
let new_item_desc = req.body.item_desc;
let new_quantity = req.body.quantity;
let new_unit_price = req.body.unit_price;
let new_total_cost = new_quantity * new_unit_price;
let new_status = req.body.status;
let new_priority = req.body.priority;
await RequestPermissionOrderSchema.findByIdAndUpdate( update_orderId, {
$set: {
item: new_item,
item_desc: new_item_desc,
quantity: new_quantity,
unit_price: new_unit_price,
total_cost: new_total_cost,
status: new_status,
priority: new_priority,
directOrder: false
}
},
{ new: true, useFindAndModify: false}, function (err, docs) {
if (err) {
console.log(err);
res.send(err);
} else {
console.log("Updated Request Permission Order : ", docs);
res.json(docs);
}
});
});
$set: { ... }
下指定的所有属性。但是执行时,在控制台中 的输出如下:
updated Request Permission Order : null
我还要确保 _id
在mongoDB数据库中是否可用以及该对象ID是否存在。我似乎找不到我做错了什么。真的感谢任何帮助!
另外,请注意,我想通过MongoDB自动生成的 _id
与每个文档进行更新。
答案 0 :(得分:1)
只需传递JSON对象,删除$ set
await RequestPermissionOrderSchema.findByIdAndUpdate( update_orderId, {
$set: { // REMOVE THIS $set
item: new_item,
item_desc: new_item_desc,
quantity: new_quantity,
unit_price: new_unit_price,
total_cost: new_total_cost,
status: new_status,
priority: new_priority,
directOrder: false
} // REMOVE THIS ALSO
},
仅JSON对象。