singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })El usuario hace clic en un botón y el valor de 'total_obj' se reduce en uno. El valor no tiene que ser inferior a 0. He intentado hacer esto:
singleObj = await Objects.findByIdAndUpdate( { _id: req.body.id, "total_obj": { "$lt": 0 } }, { "$set": { "total_obj": 0 } } );Pero esto se estropea cada vez que cargo la página y tengo los valores establecidos en 0. También agregué la definición en el esquema:
total_obj: { type: Number, required: true, min: 0 },Supongo que quiso decir que no quiere que su valor sea menor que 0. Necesitaría usar el operador $gt y, aunque usó $inc correctamente en el primer findByIdAndUpdate , no lo usó en el segundo.
Además, no estamos buscando solo la identificación, por lo que deberíamos usar findOneAndUpdate en su lugar.
singleObj = await Objects.findOneAndUpdate( { _id: req.body.id, "total_obj": { "$gt": 0 } }, { $inc: { "total_obj": -1 } } );Intente buscar primero la instancia de Objects y actualice el valor solo si > 0 :
const singleObj = await Objects.findById(req.body.id) if (!singleObj) // Error, obj not found if (singleObj.total_obj > 0) { singleObj.total_obj = singleObj.total_obj-1 await singleObj.save() } else { // `total_obj` is already zero }