0

I want to use a template string in a mongoose update query using typescript. The field I want to update is a Map called messages with string keys and array values of type Message. So something like

interface Message {
   content: string,
   from: string,
   ...
}
userSchema = new Schema({
   ...
   messages: {type: Map, default: new Map<string, Message[]>}
}

The keys in the map are id's of the "message-partner", e.g. a userId or a groupId. If a new message is sent from user with id senderId to user with id receiverId, I want to update both users' Maps. For example for the receiver I'm calling something like

UserModel.findByIdAndUpdate(receiverId, { $push: { `messages.${senderId}`: newMessage } })

However, this gives me the following errors:

enter image description here

Now if I change the template string to a usual string, for example:

"messages.1234"

the errors disappear. Is there any workaround to this issue, or am I doing something wrong?

sethgypt
  • 23
  • 7

1 Answers1

1

Answer: One has to use a ComputedPropertyName, see this answer.

The corrected update-query looks like this:

{ $push: { [`messages.${senderId}`]: newMessage }
sethgypt
  • 23
  • 7