How to pass a function parameter as a property in MongoDB and Typescript

I've been working on a project that involves using Mongoose to write, update, and perform other operations in a MongoDB database.

Currently, I am utilizing the updateOne() function within my own custom function. However, I am facing an issue where if I use

const resp = await seasonFixturesModel.updateOne({season_id: season_id, "fixtures.274704.id": 18535224},{$set:{"fixtures.274704.$":{} }});

with the hardcoded ID 274704, the update works correctly. Yet, I want to dynamically change this ID based on a parameter in my function, like so:

function updateMyDatabase(round_id: number){
const resp = await seasonFixturesModel.updateOne({season_id: season_id, "fixtures.round_id.id": 18535224},{$set:{"fixtures.round_id.$":{} }});
}

Can anyone provide guidance on how to achieve this? I have experimented with different solutions such as "fixtures.round_id.id", "fixtures.{round_id}.id", and "fixtures.${round_id}.id", but none seem to be effective.

Answer №1

To enclose the key in square brackets, you need to wrap it inside. Within the brackets, you can insert any expression that will result in a string (or numbers, symbols). Using a template literal string is ideal for combining the values.

function updateMyDatabase(round_id: number){
  const resp = await seasonFixturesModel.updateOne(
    {  
      season_id: season_id, 
      [`fixtures.${round_id}.id`]: 18535224
    },
    {$set:{"fixtures.round_id.$":{} }}
  );
}

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

The marker.js 2 documentation states that integrating marker.js with React poses compatibility issues when using next.js

I have followed the documentation for using this in my next.js app, but unfortunately, it's not functioning as expected. There are no errors, but nothing happens when I click on the image. It appears that this library may not be compatible with Next. ...

Verification of symmetrical file formatting

When dealing with three separate file upload inputs, the challenge is to ensure that the uploaded files are not duplicates. Additionally, if the user selects image format files (such as png, jpg, jpeg), they must select all three inputs in image format. On ...

When someone visits a site using Next.js, the redirect feature may successfully load the site, but it fails to actually

I have a serverless logout function in Next.js: import magic from './magic'; import { withSessionRoute } from './sessions'; export default withSessionRoute(async function logoutHandler( request, response, ) { try { if (reques ...

Show an array of arrays using a visual table representation

I am working with an Array of arrays in my data, and they are structured like this : https://i.sstatic.net/3grh6.png Now, I am trying to showcase this array in a table, but all I am getting is a blank page. Here is the HTML code for the table (I have incl ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

Which is more efficient: storing thousands of objects in one Mongo doc, or creating thousands of individual docs each holding one object?

Within my web application, an authenticated user has the ability to select songs from their Spotify playlist to play at an event. I would like non-authenticated guests to be able to view these selected songs on a dynamically generated React route and vote ...

Error: Node.js + MongoDB cluster fails to launch

I'm currently in the process of deploying a Node 6.0 server alongside mongo 3.2 on openshift. I successfully created an app using the Node DIY cartridge, which can be found here: Additionally, I added a mongo DIY cartridge as well: https://raw.github ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Tips for querying MongoDB schemas that reference other schemas in the field?

Looking to search for a product by its name within the DOC Schema. However, the products are stored as references in another Product Schema with the _id. Below you can find the code snippets to understand the structure: DOC Schema import mongoose from &qu ...

Submit a POST request to my MongoDB database

Greetings everyone, I am a beginner in the world of coding and currently tackling a project where I need help. The project involves creating a website where the client or customer can make a deposit. When they click submit, the form should send a post requ ...

Tips for avoiding the exposure of full user models in the jade template

As I work on the login functionality of my project, I'm utilizing express, passport-local, and mongoose. My code includes a series of routes: module.exports = function (app) { app.get('/', function (req, res) { res.render(' ...

The element 'nz-list-item-meta-title' in NG-ZORRO is unrecognized

After installing NG-ZORRO for my project, I decided to start by incorporating their list component. However, I encountered errors with elements such as: 'nz-list-item-meta-title' and 'nz-list-item-action' not being recognized. I have e ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

When trying to use the exported Ionic 3 class in TypeScript, the error "Cannot find name 'ClassName'" occurs

When working on my Ionic 3 Application, I encountered an error stating "Cannot find name" when trying to use certain plugins. I initially imported the plugin like this: import { AndroidPermissions } from '@ionic-native/android-permissions'; and ...

Changing a particular value within a JSON field in MongoDB using Mongoose on a Linux system

I am currently working on modifying a specific value within a json-type field. The structure of my document schema is as follows: character { name: {type: string}, experience: {type: json} ... } I always ensure that the 'experience&apos ...

assign data points to Chart.js

I have written a piece of code that counts the occurrences of each date in an array: let month = []; let current; let count = 0; chartDates = chartDates.sort() for (var i = 0; i < chartDates.length; i++) { month.push(chartDates[i].split('-&ap ...

Ensure that the method is triggered

I have a builder class that implements an interface which it is expected to build. However, I would like to enforce one method of this class to be called at compile time, rather than runtime. The class is designed to be used as a chain of method calls and ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...