简体   繁体   English

在 For 循环中使用 Mongoose FindoneAndUpdate

[英]Using Mongoose FindoneAndUpdate In A For Loop

I'm making a Use command with Mongoose and Discordjs.我正在使用 Mongoose 和 Discordjs 进行使用命令。 It's all working fine but there is a problem with database.一切正常,但数据库有问题。

When I try to use it, like .use box 5 it has to remove 5 boxes from database, but it only removes 1.当我尝试使用它时,例如.use box 5它必须从数据库中删除 5 个框,但它只删除 1 个。

My code:我的代码:

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")
  }
}

There is no error by the way.顺便说一句,没有错误。 Also I've embedded some screenshots of when I use the command:我还嵌入了一些使用命令时的屏幕截图:

使用命令

使用命令后的库存

I had 46 before I used the command;在我使用命令之前我有 46 个; after using (5) boxes I have 45.使用(5)个盒子后,我有 45 个。

Try this:试试这个:

profileModel.findOneAndUpdate({ userID: message.author.id },{"$pull": { "inventory": obj } },{returnNewDocument: true})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM