Home > Blockchain >  Create a generic method for adding data into an array in a collection
Create a generic method for adding data into an array in a collection

Time:04-12

I am new to Typescript. I am creating a generic method to push data into an array in a mongoose collection. Data does not get passed in the fieldName parameter in the below function as it is the Key field in the $set operator. Kindly help me to pass value dynamically to the Key field of $set operator to make this function workable.

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);
            }
        });
}

CodePudding user response:

To use variables as keys in an object in JavaScript you need to put them in square brackets.

{
  $set: {
    [fieldName] : fieldData
  }
}
  • Related