Home > Blockchain >  Mongo DB/Typescript how to pass function parameter as property
Mongo DB/Typescript how to pass function parameter as property

Time:10-16

I'm working on a project where I'm using mongoose for writing, updating and so on in Mongo DB.

I call updateOne() function in my own custom function, but the thing is if I use

const resp = await seasonFixturesModel.updateOne({season_id: season_id, "fixtures.274704.id": 18535224},{$set:{"fixtures.274704.$":{} }});

where 274704 is hardcoded ID, updated works like it should, but I want to have this ID changed based on my own function parameter e.g.:

function updateMyDatabase(round_id: number){
const resp = await seasonFixturesModel.updateOne({season_id: season_id, "fixtures.round_id.id": 18535224},{$set:{"fixtures.round_id.$":{} }});
}

Does anybody know how to do that? I tried many solutions such as "fixtures.round_id.id", "fixtures.{round_id}.id", "fixtures.${round_id}.id" but non of them work.

CodePudding user response:

You will have two wrap the key into square brackets. In there, you can put any expression which will evaluate into a string (or numbers, symbols). A template literal string will do the job to concatenate the values.

function updateMyDatabase(round_id: number){
  const resp = await seasonFixturesModel.updateOne(
    {  
      season_id: season_id, 
      [`fixtures.${round_id}.id`]: 18535224
    },
    {$set:{"fixtures.round_id.$":{} }}
  );
}
  • Related