const db = mongoose.connection
let orderTotal = 0
//try with async iterators
let session = await db.startSession()
try {
session.startTransaction()
for await (const item of req.body) {
for await (const val of item.values) {
await ProdIns.findOneAndUpdate({
SKU: item.SKU,
categoryOptId: val.optionId,
categoryOptVal: val._id,
stockQty: { $gt: item.qty }
}, {$inc:{stockQty:-item.qty}}, { session: session })
await ProdIns.findByIdAndUpdate(val._id, { $inc: { stockQty: -item.qty } }
)
}
await Cart.findByIdAndUpdate(item._id, { $set: { completed: true } }, { session: session })
}
await session.commitTransaction()
session.endSession()
res.status(201).send()
} catch (e) {
console.log(e)
await session.abortTransaction()
res.status(500).send()
}
In the above snippet I clearly know that I dont have any matching doc in ProdIns model that has stockQty field $gt: item.qty; In this case isnt it obvious that my transaction would get aborted? if not then why? And how to make it abort if ProdIns collection does not have any matching document that has stockQty $gt item.qty.
Also I am using for loop to iterate through user’s cart items array. for every instance of the Cart items array my intent is to iterates through the variants(values) of that item and deduce the number of quantity user desires to order from ProdIns collection. Is it viable option to use async iteration? Any better alternative? Any Similar example you can give? how do you take your cart items and convert them into orders any tips on that please?