Mongoose loop through findOneAndUpdate condition statement
This could be done with an atomic update where you can ditch the initial findById()
call and include the comparison logic
if (productDB.stock > o.stock && productDB.stock > 0) { ... }
within the query as in the following:
function updateStock(o) { mongoose.model('Product').findOneAndUpdate( { "_id": o._id, "$and": [ { "stock": { "$gt": o.stock } } , { "stock": { "$gt": 0 } } ] }, { "$inc": { "stock": -(o.stock) } }, { "new": true }, // <-- returns modified document function (err, doc) { // check whether there was an update } );}