Using variables to build dynamic MongoDB/Mongoose query of nested object Using variables to build dynamic MongoDB/Mongoose query of nested object mongoose mongoose

Using variables to build dynamic MongoDB/Mongoose query of nested object


OK, I figured out how to make this happen. Posting resolution just in case another nascent developer runs into this.

app.get("/unlink/:account", async (req, res) => {    let accountType = req.params.account,        query1 = "authProviders." + accountType + "." + accountType + "Id",        query2 = "authProviders." + accountType + "." + accountType + "Email",        query3 = "authProviders." + accountType + "." + accountType + "DisplayName";    await User.update(      { _id: req.user._id },      {        $unset: {          [query1]: "",          [query2]: "",          [query3]: ""        }      }    );    res.redirect("/preferences");  });


You could do it like this :

app.get("/unlink/:account", async (req, res) => {      let accountType = req.params.account;    await User.update(      { _id: req.user._id },      {        $unset: {          authProviders[`${accountType}.${accountType}id`]: "",          authProviders[`${accountType}.${accountType}email`]: "",          authProviders[`${accountType}.${accountType}displayName`] : ""        }      }    );    res.redirect("/preferences");  });