[英]Mongoose findOneAndUpdate in a for loop using set if extist or put if doesn't
[英]Using Mongoose FindoneAndUpdate In A For Loop
我正在使用 Mongoose 和 Discordjs 進行使用命令。 一切正常,但數據庫有問題。
當我嘗試使用它時,例如.use box 5
它必須從數據庫中刪除 5 個框,但它只刪除 1 個。
我的代碼:
function random(min, max) {
return Math.round(min + Math.random() * (max - min));
}
const profileModel = require("../../models/users")
const user = await profileModel.findOne({
userID: message.author.id
})
if (!args[0]) return message.reply("WHAT THE HELL ARE YOU GOING TO USE :|")
let item = user.inventory.find(v => v.name.toLowerCase() === args[0].toLowerCase());
if (!item) {
return message.channel.send("You Dont have That Item");
}
if (item.use === false) return message.reply("This Item Is Not Usable")
function runUpdate(obj) {
return new Promise((resolve, reject) => {
profileModel.findOneAndUpdate({
userID: message.author.id
}, {
"$pull": {
"inventory": obj
}
})
.then(result => resolve())
.catch(err => reject(err))
});
};
itemusing = args[0].toLowerCase()
if (!args[1]) amount = 1
else amount = Math.floor(args[1])
console.log(amount)
if (itemusing === "box") {
if (amount > 1) {
for (let m = 0; m < amount + 2; m++) {
console.log(m)
runUpdate(item)
}
let newboxes = 0;
let coins = 0;
for (let i = 0; i < amount; i++) {
const rnd = random(1, 10)
if (rnd <= 6) abox = false
else abox = true
const amountrnd = random(1000, 5000)
if (abox === true) {
newboxes += 1
coins += amountrnd
} else {
coins += amountrnd
}
}
if (newboxes >= 1) {
await profileModel.findOneAndUpdate({
userID: message.author.id
}, {
"$inc": {
"coins": coins
}
});
await message.reply(`You Found These In ${amount} Box(s):\n\n${coins} Coins\n${newboxes} Boxes`)
} else {
message.reply(`You Found These In ${amount} Box(s):\n\n${coins} Coins`)
await profileModel.updateOne({
userID: message.author.id
}, {
"$inc": {
"coins": coins
}
});
}
} else {
message.reply("Soon")
}
}
順便說一句,沒有錯誤。 我還嵌入了一些使用命令時的屏幕截圖:
在我使用命令之前我有 46 個; 使用(5)個盒子后,我有 45 個。
試試這個:
profileModel.findOneAndUpdate({ userID: message.author.id },{"$pull": { "inventory": obj } },{returnNewDocument: true})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.