1

The title is not very clear, I'll demonstrate what I mean.

I have a document that looks something like the following...

const room_schema = new Schema({
  room_id: data.room_id,
  song_queue: [{
    _id: false,
    user_id: String,
  }],
});

The song_queue is an array. In my code I have a variable that gives me the index of the element I need to update. Let's call the variable position...

room = await Room.findOneAndUpdate(
  { 
    room_id: data.room_id 
  },
  {
    "song_queue." + position + ".user_id": data.user_id
  }
);

I need to use that variable within the key, however, the code above does not work. How can I make my logic work?

buydadip
  • 8,890
  • 22
  • 79
  • 154

1 Answers1

1

you must use brackets, and you can use template literals too, try this way:

const room = await Room.findOneAndUpdate(
      { 
        room_id: data.room_id 
      },
      {
         ["song_queue." + position + ".user_id"]: data.user_id
      }
    );
buydadip
  • 8,890
  • 22
  • 79
  • 154