Develop a universal function for inserting information into an array within a data set

I need assistance with my Typescript code. I am currently working on a method that pushes data into an array in a mongoose collection. However, the issue I'm facing is that the value is not being passed dynamically to the Key field in the $set operator using the fieldName parameter. Can someone please guide me on how to modify this function so that it works as intended?

async createStudentInfo<T>(studentId:ObjectID, fieldName: String, fieldData:Array<T>, errorMessage: String):Promise<Array<T>>{
return new Promise(async (resolve, reject) => {
            try {                
                const result = await studentModel.updateOne(
                    { "_id": studentId },
                    {
                        $set: {
                            fieldName : fieldData
                        }
                    }, 
                    {upsert:true}
                )              
                resolve(fieldData);
            }
            catch (err) {
                reject(errorMessage);
            }
        });
}

Answer №1

If you want to use variables as keys within an object in JavaScript, make sure to enclose them in square brackets.

{
  $update: {
    [variableName] : variableData
  }
}

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

What are the steps to install the latest version of Wekan on Ubuntu without any additional configurations

Wekan is a fantastic open-source Kanban Board. If you're looking to install Wekan on Ubuntu 16.04, you may encounter some challenges along the way as I did: To begin with, downloading and extracting the latest version of Wekan source code using the w ...

Unleashing the power of joint queries in Sequelize

Project.data.ts import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize'; import sequelize fr ...

Presenting information extracted from the Meteor 1.0 framework

At the beginning of my Meteor application, I import data from a JSON file using the following code: 13 if (Meteor.isServer) { 14 15 //startup 16 Meteor.startup(function () { 17 if(Plugins.find().count() === 0) { 18 var plugins_data = J ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Using the find() function in Mongo does not effectively work alongside multer in order to display a comprehensive

Recently, I created a basic CRUD API using multer/gridfs to store image files. While it successfully handles tasks like adding, deleting, and finding images by their names, there seems to be a problem with listing all the uploaded files using the find() me ...

Access denied: Unable to grant roles to user on the MongoDB database in the LIVE server, although the operation is successful when performed on a local machine

1. Different scenario:- In my primary database, which is known as portal_mongodb, there exists a user named portal_mongodba with the role permission set to {'role': 'dbOwner', 'db' : portal_mongodb}. The environment I have s ...

At what point is it appropriate for a class to incorporate an interface?

Currently working on a project and I've noticed developers using TypeScript in the following way: export class Ledger implements ILedger { LedgerID: number; CashAmmount: number; Units: number; ...

Mongoose: The remove() function will confirm as true even for items that have already been

My current code snippet always displays "User deleted" even after the user has been removed. Ideally, I would like to return a 404 error in this scenario without making excessive database queries. Is there a way to retrieve the status of userNotFound with ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

What is the recommended way to validate the length of an array when utilizing the $push

Currently, I'm facing a challenge in restricting the number of elements that a user can add to an array field within one of my schemas. The method I am employing to add these elements to the array involves using Schema.findOneAndUpdate(); along with t ...

Challenge encountered with TypeScript integration in the controller

I am currently in the process of converting a website from VB to C# and incorporating TypeScript. I have successfully managed to send the data to the controller. However, instead of redirecting to the next page, the controller redirects back to the same pa ...

What could be causing the constant appearance of empty brackets in the JSON response within Postman?

// controllers/users.js 'use strict'; var mongoose = require('mongoose'), User = mongoose.model('Users'); exports.list_all_users = function(req, res) { User.find({}, function(err, users) { if (err) ...

Loading an external javascript file dynamically within an Angular component

Currently, I'm in the process of developing an Angular application with Angular 4 and CLI. One of my challenges is integrating the SkyScanner search widget into a specific component. For reference, you can check out this Skyscanner Widget Example. T ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

Should we utilize the component @Input as a parameter for the injected service constructor, or should we opt for the ServiceFactory

Within Angular 12 lies a simplified component structured as follows: @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.less'] }) export class ListComponent implements ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

Ensure validation in Multer prior to uploading

Before uploading a file with Multer, I need to validate whether the idProject I receive is an ObjectId or if it exists in my db. However, the file gets saved first and then the validation occurs. I've attempted putting the validation logic in the ind ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

Why won't Angular 4 create the node_modules folder when using ng new to initialize a new project?

Recently reinstalled Angular and began a new project using ng new. However, I encountered issues when trying to run ng serve after creating the project and changing into its directory. On my Mac Mini, I can simply navigate to the project folder and run ng ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...