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

115
Vistas
Use variable outside the object to be the object variable

I have this code

for (var i = 0; i < lootbox.length; i++) {
  const { type } = lootbox[i]
  const query = type + "_lootbox.hunt";

  await lb.findOneAndUpdate(
    { userID: message.author.id },
    { $inc: { query: 1 } }
  );
}

the code reads the query as its own variable instead of the type + "_lootbox.hunt", is there a way to use that query inside the $inc? because I want to automate it using the loop

AKA. dynamic object key

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

0

The problem here is that you are trying to create an object on the fly, but you can not set a key like that dynamically.

To achieve that you need to prepare this object prior to use.

And, in such a case your code would be something like this,

for (var i = 0; i < lootbox.length; i++) {
  const { type } = lootbox[i]
  const query = type + "_lootbox.hunt";
  const tempObject = {}; // Creating an empty Object
  tempObject[query] = 1; // Dynamic key usage
  await lb.findOneAndUpdate(
    { userID: message.author.id },
    { $inc: tempObject } // Using the tempObject
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

As I understand what you want is this: in each iteration query becomes type + "_lootbox.hunt", for example page1_lootbox.hunt. And what you want to get is { $inc: { "page1_lootbox.hunt": 1 }}. If so, a simple solution will be

{ $inc: { [query]: 1 } }    // { $inc: { "page1_lootbox.hunt": 1 } }

Let me know if you want something different.

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