Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
Using Mongoose FindoneAndUpdate In A For Loop

I'm making a Use command with Mongoose and 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.

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:

The Use Command

The Inventory After Using The Command

I had 46 before I used the command; after using (5) boxes I have 45.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

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

or (Below should work for NodeJS)

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

Or findAndModify() instead of findOneAndUpdate()

Disclaimer: I have not run above code. Based on my knowledge about findAndModify and findOneAndUpdate, I gave answer.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda