How to set dynamic key while updating via mongoose in NodeJS, Express

Viewed 82

Since there are a lot of keys that I want to update from just one function. I need to understand how I can set the key to update dynamically.

static async updateProfile(req, res, next) {

    const userId = req.body.userId;

    // I am receiving the key in body that needs to be updated
    const key = req.body.key;
    const value = req.body.value;

    const toUpdate = {
        userId: userId,
        //here I want the key to be dynamic
        key: value
    };

    try {
        const updateNow = await Profile.findOneAndUpdate(
          { userId: userId },
          toUpdate,
          { upsert: true }
        );
    } catch (err) {
        console.log(err);
    }
}
1 Answers

const toUpdate = {
  ...
  [key]: value
}

or 

toUpdate[key] = value;

or

toUpdate[`${key}`] = value;

any of the above works

Related