javascriptmongodbmongodb-realm

Dynamic key name for mongodb Realm


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!


Solution

  • 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.