2

I building a game thingy where you can trade and stuff. I'm currently making the admin command for it, so that you can give members amounts of materials. Here is the code:

      try {
        const targetData = await profileModel.findOne({ userID: target.id });
        if (!targetData) {
          return message.channel.send(config.basemessages.messagesaccountmissing);
        }
        await profileModel.findOneAndUpdate(
          {
            userID: target.id,
          },
          {
            $inc: {
              bank: amount,
            },
          }
        );

        message.channel.send(`The targeted member has been given \`${amount}\` amount of \`${material}\`.`)
      } catch (err) {
        console.log(err);
        message.channel.send(`Error executing command. EC: \`${config.errorcodes.err2}\`.`) // Error Systeem
      }

Since I have 200+ different items, it would be inefficient if I copy this block 200+ times just to give someone a item. The problem is that bank should be the exact name of a row in a MongoDB document. I just discovered that you can't make that a variable (or so I think). I want to replace that with for example material, where material is args[1] (the perimeter). Example usage:

$give @member iron 40
  • Member = the target Discord member (args[0])
  • Iron = the material that I want to increase (args[1])
  • 40 = amount to increase (args[2])

I hope it's clear what I mean. Is there a work around this? (Only the bank perimeter doesn't work, the amount does work with a variable).

  • 1
    Does this answer your question? [How to create an object property from a variable value in JavaScript?](https://stackoverflow.com/questions/2241875/how-to-create-an-object-property-from-a-variable-value-in-javascript) – mhodges Jun 08 '22 at 15:20
  • It seems like all you're wanting to do is dynamically add a property to an object. This can be done a few different ways with the link provided above – mhodges Jun 08 '22 at 15:21
  • Since I am not very experienced with Javascript, I don't see a direct link between my problem and the provided link. Can you help me further? @mhodges – Puffin Kwadraat Jun 08 '22 at 15:23
  • 1
    "The problem is that bank should be the exact name of a row in a MongoDB document. I just discovered that you can't make that a variable (or so I think)." You can make it a variable, as the link shows. For example: `{ $inc: { [colToChange]: amount } }`. If you simply put brackets around an object property name, it will evaluate it as a JS expression, meaning you can put a variable in there and it will evaluate it as the value of that variable and use that value as the object property. So, if your `colToChange = 'bank'` or `colToChange = 'iron'`, etc. it will update that property respectively. – mhodges Jun 08 '22 at 15:25
  • 1
    Thanks! With the brackets around the variable name it worked! – Puffin Kwadraat Jun 08 '22 at 15:28

0 Answers0