javascript - 在 For 循环中使用 Mongoose FindoneAndUpdate
问题描述
我正在使用 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})
或(以下应该适用于NodeJS)
profileModel.findOneAndUpdate({ userID: message.author.id },{"$pull": { "inventory": obj } },{returnOriginal: false})
或者findAndModify()
代替findOneAndUpdate()
免责声明:我没有运行上面的代码。根据我对 findAndModify 和 findOneAndUpdate 的了解,我给出了答案。
推荐阅读
- sql - Oracle 表大小
- python - 尝试运行 pygame 时出错:“视频系统未初始化”
- python - 修改一列的值,在原值后面加一个词
- java - 如何在xml属性中调用java方法
- python - 如何使用带有日期的 plotly graph_objects scatter
- css - 试图“转换:旋转()”
使用样式组件的元素 - spring-security - 如何使用 Vue.js 正确配置 Spring Security 5 OAuth?
- node.js - 如何在 mocha chai 中发送表单数据格式的正文
- python-3.x - 使用 boto3 检查 s3 的存储桶中是否存在目录或子目录
- javascript - 在 Firefox 的 WebExtensions 中通知/提醒用户的方法