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
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
);
}
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.