我在 mongoose 上的更新查詢有問題。我不確定為什么在更新特定物件后其他物件會被洗掉。代碼在我更新時有效,但在那之后,陣列內的其余物件將被洗掉/移除。從字面上看,所有剩余的物件都會在更新請求后被洗掉。
export const updateProduct = async (req,res) => {
const { id } = req.params;
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'Invalid ID' });
await OwnerModels.findOneAndUpdate({'_id': id, store:{$elemMatch: {productname: req.body.store[0].productname }}},
{$set:
{
store:
{
productname: req.body.store[0].productname,
price: req.body.store[0].price,
quantity: req.body.store[0].quantity,
categoryfilter: req.body.store[0].categoryfilter,
description: req.body.store[0].description,
timestamp: req.body.store[0].timestamp
}
}
}, // list fields you like to change
{'new': true, 'safe': true, 'upsert': true});
} catch (error) {
res.status(404).json(error)
} }
uj5u.com熱心網友回復:
我不確定為什么在更新特定物件后其他物件會被洗掉。
因為您正在更新整個物件,它將替換資料庫中現有的存盤物件陣列,
您需要使用 arraFilters,并且upsert在更新的物件陣列中無效,因此我已發表評論,
await OwnerModels.findOneAndUpdate(
{
'_id': id,
store:{
$elemMatch: {
productname: req.body.store[0].productname
}
}
},
{
$set: {
store: {
"store.$[s].productname": req.body.store[0].productname,
"store.$[s].price": req.body.store[0].price,
"store.$[s].quantity": req.body.store[0].quantity,
"store.$[s].categoryfilter": req.body.store[0].categoryfilter,
"store.$[s].description": req.body.store[0].description,
"store.$[s].timestamp": req.body.store[0].timestamp
}
}
},
{
'arrayFilters': [
{ "s.productname": req.body.store[0].productname }
],
'new': true,
'safe': true,
// 'upsert': true
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391900.html
標籤:javascript 节点.js MongoDB 猫鼬
