使用变量构建嵌套对象的动态 MongoDB/Mongoose 查询

Bri*_*mel 3 mongoose mongodb node.js ecmascript-6 template-literals

我的应用程序有 4 个相同的 Node/Express API 路由,旨在删除 MongoDB 数据库中的嵌套对象属性。这 4 个路由之间唯一的语法区别是字符串值(“facebook”、“google”、“twitter”或“github”)。这是四个路由之一:

  app.get("/unlink/facebook", async (req, res) => {
    await User.update(
      { _id: req.user._id },
      {
        $unset: {
          "authProviders.facebook.facebookId": "",
          "authProviders.facebook.facebookDisplayName": "",
          "authProviders.facebook.facebookEmail": ""
        }
      }
    );
    res.redirect("/preferences");
  });
Run Code Online (Sandbox Code Playgroud)

我的目标是通过将参数添加到 Express 路由的 URL 上,将这四个路由重构为单个端点,该参数将成为表示四种社交媒体帐户类型之一的字符串变量。该路线的重点是动态确定MongoDB用户文档中的authProviders对象中要$unset(删除)哪个社交媒体帐户属性。

我尝试构建 MongoDB 查询以使用 ES6 模板文字访问必要的对象属性,但是收到错误:"SyntaxError: Unexpected template string"

下面是我尝试使用 ES6 模板文字和社交媒体变量重构为单一端点的代码:

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

这是 MongoDB 文档:

在此输入图像描述

关于如何使这项工作有任何想法吗?我似乎无法弄清楚如何构造 MongoDB 查询以使用变量访问对象属性。

Bri*_*mel 5

好的,我知道如何实现这一点。发布解决方案,以防其他新手开发人员遇到此问题。

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");
  });
Run Code Online (Sandbox Code Playgroud)