Using template strings in a Mongoose update query when working with TypeScript

When working with a mongoose update query in typescript, I am trying to incorporate a template string. The specific field I need to update is a Map named messages, which consists of string keys and array values of type Message.

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

The keys within the map represent ids of the "message-partner", such as userIds or groupIds. In the case of a new message being sent from a user with the id senderId to a user with the id receiverId, I intend to update both users' Maps. For instance, for the receiver, I would execute something similar to:

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

However, this approach results in some errors:

https://i.sstatic.net/dSJrw.png

If I modify the template string to a regular string instead, like so:

"messages.1234"

The errors disappear. I am curious if there are any workarounds for this issue, or if I am overlooking something in my implementation?

Answer №1

Solution: In order to achieve the desired outcome, it is necessary to implement a ComputedPropertyName. To find out more about this technique, refer to this helpful resource.

The revised update-query should be structured as follows:

{ $push: { [`messages.${senderId}`]: newMessage }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to establish a connection to the database with nodejs

I'm completely new to nodejs and I can't quite understand what's really happening here. I have a simple login page where, as the user inputs their details, they should be directed to the home page. Before that happens, I check if the usernam ...

Angular2 routing directs me to a different URL path

In my Angular2 web application, I have set up the following routes: '', '/app', '/login', '/signin', '/validate', '/error', '**': I've defined a route configuration in app.router.t ...

What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below: @Component({ selector: 'item-selector&apos ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Expressjs makes it easy to upload audio files to your website

Currently, I'm developing a music app and I'm looking for the best way to upload an audio file in my ExpressJS application. Is it possible to use Cloudinary or is there another method that is more efficient? I attempted to follow the same proces ...

Utility managing various asynchronous tasks through observables and signaling mechanism

Looking for a Signal-based utility to monitor the status of multiple asynchronous operations carried out with observables (such as HTTP calls). This will enable using those signals in Components that utilize the OnPush change detection strategy. Imagine h ...

Executing child processes in the Mean Stack environment involves utilizing the `child_process`

I am working on a Mean application that utilizes nodejs, angularjs and expressjs. In my setup, the server is called from the angular controller like this: Angular Controller.js $http.post('/sample', $scope.sample).then(function (response) ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

Retrieve MongoDB documents that meet all conditions set by their subdocuments

Being a beginner with Mongo, I have a question that may seem trivial. Thank you for your patience :) In my Mongo database, documents are categorized as either valid or archive. A document is considered valid if any of its revisions.validTo date field is e ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Creating custom paths by using Express Route Parameters may lead to the generation of

Currently, I am in the process of developing a to-do list application and facing some challenges while incorporating custom routes utilizing 'Express Route Parameters'. Everything was functioning smoothly until I attempted to implement these cust ...

Creating a dynamic selection in Angular without duplicate values

How can I prevent repetition of values when creating a dynamic select based on an object fetched from a database? Below is the HTML code: <router-outlet></router-outlet> <hr> <div class="row"> <div class="col-xs-12"> & ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: https://i.sstatic.net/SnXFZ.png Next to the contact component, I have placed anothe ...

Secure a reliable result from a function utilizing switch statements in Typescript

There's a function in my code that takes an argument with three possible values and returns a corresponding value based on this argument. Essentially, it can return one of three different values. To achieve this, I've implemented a switch statem ...

Is it possible to retrieve the ObjectID in MongoDB using Python while submitting a data form?

For a course milestone, I am working on a recipe blog using Python, Flask, and MongoDB. Below is the Python code I have written, although I am just a student so please excuse any imperfections: @app.route('/insert_recipe', methods=['POST ...