【发布时间】:2022-01-10 15:42:55
【问题描述】:
我有一个数据结构:
{
field: 1,
field: 3,
field: [
{ _id: xxx , subfield: 1 },
{ _id: xxx , subfield: 1 },
]
}
我需要更新数组中的某个元素。
到目前为止,我只能通过拉出旧对象并推入新对象来做到这一点,但这会改变文件顺序。
我的实现:
const product = await ProductModel.findOne({ _id: productID });
const price = product.prices.find( (price: any) => price._id == id );
if(!price) {
throw {
type: 'ProductPriceError',
code: 404,
message: `Coundn't find price with provided ID: ${id}`,
success: false,
}
}
product.prices.pull({ _id: id })
product.prices.push(Object.assign(price, payload))
await product.save()
我想知道是否有任何原子方式来实现它。因为这种方法似乎并不安全。
【问题讨论】:
标签: javascript mongodb mongoose nodes