I have a list/collection and I need to check if a product exist by the same id, I need to increase the quantity else add the product. I am able to add product if id dosen't exist but I am not able to increase quanity if the product dosen't exist.
cart_items = [
{
"id": 144,
"created_at": "2019-04-04 14:42:04",
"updated_at": "2019-04-04 14:42:04",
"cart_id": "3",
"client_id": "83",
"product_id": "6",
"quantity": "1",
"price": "1500",
"name": "Cucumber (2Pcs)",
"image": "products/es4eGjkgQ6MvzTaMyX4iXWjcSX03mVk3QB9oODWk.jpeg",
},
{
"id": 145,
"created_at": "2019-04-04 14:42:09",
"updated_at": "2019-04-04 14:42:09",
"cart_id": "3",
"client_id": "83",
"product_id": "5",
"quantity": "1",
"price": "2000",
"name": "Cauliflower",
"image": "products/lVZ31zORzltyVIDXhHoCWUgjTlal7cWd7pI8DL2V.jpeg",
}
]
Edit:
I have implemented this till now:
if (snapshot.data.data()["Array"][0]["id"] == 1489) {
FirebaseFirestore.instance
.collection("text")
.doc("qjxuj18kfcOpqBVLWjVD")
.update({
'Array': FieldValue.arrayUnion(
[
{
"id": 14999,
"created_at": "2019-04-04 14:42:09",
"updated_at": "2019-04-04 14:42:09",
"cart_id": "3",
"client_id": "83",
"product_id": "5",
"quantity": 1,
"price": "2000",
"name": "Cauliflower",
"image":
"products/lVZ31zORzltyVIDXhHoCWUgjTlal7cWd7pI8DL2V.jpeg",
}
],
),
});
} else {
print(snapshot.data.data()["Array"][0]["id"]);
FirebaseFirestore.instance
.collection("test")
.doc("qjxuj18kfcOpqBVLWjVD")
.update(
{
'Array'[0]["id"]:
},
);
}
I am using Fieldvalue.ArrayUnion to check if a value exist, now I want to implement Fieldvalue.increment() . Reason: updating and uploading the whole array is not convinent . Everything is working fine but getting stuck at the else part ...
Thank you in advance.
question from:
https://stackoverflow.com/questions/65876045/add-map-if-it-dosent-exist-else-increase-quantity-if-it-exists-in-the-array 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…