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?

0

1 Answer 1

1

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

The corrected update-query looks like this:

{ $push: { [`messages.${senderId}`]: newMessage }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.