【发布时间】:2022-01-24 13:25:31
【问题描述】:
我在 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)
} }
【问题讨论】:
标签: javascript node.js mongodb mongoose