這是更新宣告:
const cart = await Cart.findOneAndUpdate({
userId: userId,
'items._id': itemId,
'items.product': productId,
'items.size': size,
'items.color': color,
}, {
$set: {
'items.$.quantity': quantity
}
}, {
new: true
}).populate({
path: 'items.product',
model: 'Product'
})
這是要應用于陣列的新數量:
newQuantity {
itemId: '625065c99edbfad52ac3afce',
productId: '6205a4565c0caba6fb39cd5d',
size: '3',
quantity: '3',
color: 'blue2'
}
這是資料庫中的資料,陣列的第一項更新為新數量,而不是第二項滿足上面顯示的查詢條件。
{
"_id": {
"$oid": "623a1f208ea52c030dc331a5"
},
"userId": {
"$oid": "623a1f208ea52c030dc331a3"
},
"items": [
{
"quantity": 2,
"product": {
"$oid": "6205a4565c0caba6fb39cd5d"
},
"size": "3",
"color": "blue1",
"prodImage": "mom-jeans-3.1.png",
"_id": {
"$oid": "625065c69edbfad52ac3afc2"
}
},
{
"quantity": 1,
"product": {
"$oid": "6205a4565c0caba6fb39cd5d"
},
"size": "3",
"color": "blue2",
"prodImage": "mom-jeans-5.1.png",
"_id": {
"$oid": "625065c99edbfad52ac3afce"
}
},
{
"quantity": 1,
"product": {
"$oid": "6205a4565c0caba6fb39cd5d"
},
"size": "3",
"color": "blue3",
"prodImage": "mom-jeans-4.1.png",
"_id": {
"$oid": "625065cc9edbfad52ac3afdc"
}
}
],
"__v": 0
}
uj5u.com熱心網友回復:
您可以使用陣列過濾器來獲得所需的輸出:
into find 查詢將userId過濾所有檔案,陣列過濾器將在陣列中找到與您的條件匹配的物件。
db.collection.update({
"userId": userId
},
{
"$set": {
"items.$[item].quantity": quantity
}
},
{
"arrayFilters": [
{
"item._id": itemId,
"item.product": productId,
"item.size": size,
"item.color": color
}
]
})
這里的例子
uj5u.com熱心網友回復:
'$' 運算子僅更新找到的第一個元素。
您應該使用 $[] 運算子:
const cart = await Cart.findOneAndUpdate({
userId: userId,
'items._id': itemId,
'items.product': productId,
'items.size': size,
'items.color': color,
}, {
$set: {
'items.$[].quantity': quantity
}
}, {
new: true
}).populate({
path: 'items.product',
model: 'Product'
})
嘗試一下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457726.html
標籤:mongodb
