我在 Mongoose 中有一個 Cart 架構,包括 CartItems 作為物件陣列。
{
_id: string;
items: [
{
product: string;
options: {
size: string;
color: string;
}
quantity: number;
}
]
}
在這種情況下,是否可以在產品和選項不匹配時推送專案或在匹配時添加數量?
這是我嘗試過但不起作用的代碼。
Cart.findByIdAndUpdate(_id, {
items: {
$cond: [
{
// Does not work
$elemMatch: {
product,
"options.color": options.color,
"options.size": options.size,
},
},
{
// Should add quantity where it is matched.
},
{
$push: {
product,
productName,
options,
quantity,
},
},
],
},
});
uj5u.com熱心網友回復:
詢問
- 管道更新需要 MongoDB >= 4.2
newProduct是你要添加的產品(一個js變數)- 檢查產品是否已存在 => 添加不存在?場地
- 如果不存在則將其添加到最后
- 否則映射以找到它并更新數量
- 取消設定 2 個欄位
newProduct和not-exists
*它可以讀取 2 次陣列,也可以使用替代方法,$reduce但如果您有很多產品,$concatArrays則在 reduce 中速度很慢,因此這是更快的解決方案(即使 reduce 只讀取陣列 1 次)
*您需要一種使用管道進行更新的方法,我不知道 mongoose 是否已更新以支持它,我們是 MongoDB 5,所以我猜它會是(java 是),在最壞的情況下,您可以使用updateCommand并呼叫它runCommand(...)
測驗代碼在這里
update({"_id" : "1"},
[{"$set":
{"newProduct":
{"product":"p1",
"options":{"size":"s1", "color":"c1"},
"quantity":1}}},
{"$set":
{"not-exists?":
{"$eq":
[{"$filter":
{"input":"$items",
"cond":
{"$and":
[{"$eq":["$$this.product", "$newProduct.product"]},
{"$eq":["$$this.options.size", "$newProduct.options.size"]},
{"$eq":["$$this.options.color", "$newProduct.options.color"]}]}}},
[]]}}},
{"$set":
{"items":
{"$cond":
["$not-exists?", {"$concatArrays":["$items", ["$newProduct"]]},
{"$map":
{"input":"$items",
"in":
{"$cond":
[{"$and":
[{"$eq":["$$this.product", "$newProduct.product"]},
{"$eq":["$$this.options.size", "$newProduct.options.size"]},
{"$eq":["$$this.options.color", "$newProduct.options.color"]}]},
{"$mergeObjects":
["$$this", {"quantity":{"$add":["$$this.quantity", 1]}}]},
"$$this"]}}}]}}},
{"$unset":["not-exists?", "newProduct"]}])
查詢2
- 如果您不想使用更新管道,則可以使用更多查詢來完成
檢查是否存在
db.collection.find({
"_id" : "1",
"items": {
"$elemMatch": {
"product": "p1",
"options": {
"size": "s1",
"color": "c1"
}
}
}
})
如果不存在
db.collection.update({
"_id": "1"
},
{
"$push": {
"items": "NEWITEM" //put here the new object
}
})
否則如果存在
db.collection.update({"_id" : "1"},
{
"$inc": {
"items.$[i].quantity": 1
}
},
{
arrayFilters: [
{
"i.product": "p1",
"i.options.size": "s1",
"i.options.color": "c1"
}
]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/402942.html
標籤:
