0

I'm making a digital Christmas Kalendar for a friend. Every day he can claim a Steam game.

So in mongodb in the user account that I made for him there is a key called codes (object). The structure is as follows:

_id: blbalbalba
codes: {
   1 : {
      title: GTA V,
      code: AISHD-SDAH-HAUd, 
      claimed_at: ,
   },
   2 : {
      title: Fortnite,
      code: HHF7-d88a-88fa,
      claimed_at: ,
   }
}

Just example data. Now in the client app, when button (door) 7 is pressed/opened I want to insert the current date to the key "claimed_at" in the object with key name "7".

I tried some variations of:

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set: {  "codes.`${door_number}`.date_claimed" : date,   
  } 
  }
);

But this doesn't work. What did work was: "codes.5.date_claimed". So a static path. In that case the object with name 5 got it's date_claimed key updated. But how do I use a dynamic path with a variable instead of a number?

Thanks in advance!

Nilom
  • 13
  • 3

1 Answers1

0

If you know the variable value before calling the query i think both of the bellow can work.

var door_number=5;
var date= new Date("...");

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set : { ["codes."+door_number+".date_claimed"] : date}}
);
var door_number=5;
var date= new Date("...");

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set : { [`codes.${door_number}.date_claimed`] : date}}
);

If the dynamic behaviour is based on information on the database, send if you can sample data and expected output, so we know what you need.

Takis
  • 8,314
  • 2
  • 14
  • 25
  • Thank you very much! It worked flawlessly. I missed the [ ]. And door number is just created locally client side. Depending on the calendar door being opened. – Nilom Nov 19 '21 at 21:18