Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda