Search code examples
reactjsmongodbmeteor

How to update a document with dynamic variable and nested objects in Mongodb


I have documents, each with the following structure:

  {
   ...
   "Lessons": [],
   "Students": { 
      "Monday": {
      },
      "Tuesday": {
      },
      ...
    },
   "CampYear": "aprs22",
  }

What I'm after is to dynamically insert data into one of the day objects ("Monday", etc). I have the day coming in dynamically as well as a name and times. So, what the document would look like after the dynamic insert using "Monday", "PHOEBE SMITH", "1:00" and "2:00" would be:

  {
   ...
   "Lessons": [],
   "Students": { 
      "Monday": {
        "PHEOBE SMITH": ["1:00", "2:00"]
      },
      "Tuesday": {
      },
      ...
    },
   "CampYear": "aprs22",
  }

I thought of trying something like:

  scheduleCamper(camper, time1, time2, day) {
    Programs.update({ _id: targetTeacherId }, { $set: { 'Students[day]': { camper: [time1, time2]}} });

But this is wrong. Not sure how to handle this insert.


Solution

  • Two options:

    const modifier = {};
    modifier.Students[day] = { [camper]: [time1, time2]};
    Programs.update({ _id: targetTeacherId }, { $set: modifier });
    

    or:

    Programs.update({ _id: targetTeacherId }, { $set: {
      [`Students.${day}`]: { [camper]: [time1, time2]}
    }});