ウェブサイト検索

javascript - NodeJS、Expressでmongooseを使って更新する際に動的なキーを設定する方法


1つの関数から更新したいキーがたくさんあるので、どのようにしてキーを動的に設定して更新できるかを理解する必要があります。

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

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

or 

toUpdate[key] = value;

or

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

any of the above works