singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })
用戶單擊一個按鈕,“total_obj”的值減一。該值不必小于 0。我嘗試過這樣做:
singleObj = await Objects.findByIdAndUpdate(
{ _id: req.body.id, "total_obj": { "$lt": 0 } },
{ "$set": { "total_obj": 0 } }
);
但這每次我加載頁面時都會搞砸,并且我將值設定為 0。我還添加了架構上的定義:
total_obj: {
type: Number,
required: true,
min: 0
},
uj5u.com熱心網友回復:
我假設您的意思是您不希望您的值小于 0。您需要使用$gt運算子,并且雖然您$inc在第一個中正確findByIdAndUpdate使用但在第二個中沒有使用它。
此外,我們不只是在尋找 id 所以我們應該使用它findOneAndUpdate。
singleObj = await Objects.findOneAndUpdate(
{ _id: req.body.id, "total_obj": { "$gt": 0 } },
{ $inc: { "total_obj": -1 } }
);
uj5u.com熱心網友回復:
嘗試首先獲取Objects實體并僅在以下情況下更新值> 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477733.html
