![](/img/trans.png)
[英]Update or push object into nested array in found document mongoose
[英]Is there a way to update an object in an array of a document by query in Mongoose?
我有一個數據結構:
{
field: 1,
field: 3,
field: [
{ _id: xxx , subfield: 1 },
{ _id: xxx , subfield: 1 },
]
}
我需要更新數組中的某個元素。
到目前為止,我只能通過拔出舊的 object 並推入一個新的來做到這一點,但這會改變文件順序。
我的實現:
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()
我想知道是否有任何原子方式來實現它。 因為這種方法似乎並不安全。
是的,如果您能找到它,您可以更新陣列中的特定 object。 看看這里的位置 '$' 運算符。
您當前使用 mongoose 的實現將有點像這樣:
await ProductModel.updateOne(
{ _id: productID, 'prices._id': id },//Finding Product with the particular price
{ $set: { 'prices.$.subField': subFieldValue } },
);
注意price.$.subField中的“$”符號。 MongoDB 足夠聰明,只更新查詢找到的索引處的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.