Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!