【问题标题】:Handling Users with MongoDB Stitch App within Atlas Cluster在 Atlas Cluster 中使用 MongoDB Stitch App 处理用户
【发布时间】:2019-07-15 20:27:18
【问题描述】:

我有一个 MongoDB Stitch 应用程序,它使用电子邮件/密码身份验证。这会在 Stitch App 中创建用户,我可以在页面上进行身份验证。我的数据库也有一个 MongoDB Atlas Cluster。在集群中,我有一个带有项目名称的数据库,然后是一个用于“匹配”的集合。因此,当我将“匹配”插入集合时,我可以从 Stitch 发送经过身份验证的用户 ID,这样我就有办法查询特定用户的所有匹配。但是如何在缝合中向“用户”集合添加附加值?该用户部分在 Stitch 中使用您选择的任何身份验证类型(电子邮件/密码)预先打包。但是对于我的应用程序,我希望能够在“用户”集合上存储“MatchesWon”或“GamePreference”字段之类的内容。

我是否应该像在集群中为“匹配”创建一个集合一样为“用户”创建一个集合,然后插入从 Stitch 提供的用户 ID 并处理该集合中的字段?好像我会复制用户数据,但我不确定我是否理解另一种方法。仍在学习中,感谢任何反馈/建议。

【问题讨论】:

    标签: reactjs mongodb mongodb-atlas mongodb-stitch mongodb-cluster


    【解决方案1】:

    目前没有办法将您自己的数据存储在内部用户对象上。相反,您可以使用身份验证触发器来管理用户。以下sn-p取自这些docs

    exports = function(authEvent){
       // Only run if this event is for a newly created user.
       if (authEvent.operationType !== "CREATE") { return }
    
       // Get the internal `user` document
       const { user } = authEvent;
    
       const users = context.services.get("mongodb-atlas")
           .db("myApplication")
           .collection("users");
    
       const isLinkedUser = user.identities.length > 1;
    
       if (isLinkedUser) {
            const { identities } = user;
            return users.updateOne(
                { id: user.id },
                { $set: { identities } }
            )
    
        } else {
            return users.insertOne({ _id: user.id, ...user })
                 .catch(console.error)
        }
    };
    

    【讨论】:

    • 谢谢,完全错过了文档中的那部分。听起来创建一个用户集合是创建 Stitch 函数来触发的方法。
    【解决方案2】:

    MongoDB 以非常快的速度进行创新 - 虽然在 2019 年没有办法优雅地做到这一点,但现在有了。您现在可以在 MongoDB 领域启用自定义用户数据! (https://docs.mongodb.com/realm/users/enable-custom-user-data/)

    https://docs.mongodb.com/realm/sdk/node/advanced/access-custom-user-data

    const user = context.user;
    user.custom_data.primaryLanguage == "English";
    

    --

    {
      id: '5f1f216e82df4a7979f9da93',
      type: 'normal',
      custom_data: {
        _id: '5f20d083a37057d55edbdd57',
        userID: '5f1f216e82df4a7979f9da93',
        primaryLanguage: 'English',
      },
      data: { email: 'test@test.com' },
      identities: [
        { id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' }
      ]
    }
    

    --

    const customUserData = await user.refreshCustomData()
    console.log(customUserData);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-27
      • 2020-04-06
      • 2020-07-05
      • 2019-08-31
      • 2020-09-27
      • 2021-01-05
      • 2018-08-15
      • 2019-09-12
      相关资源
      最近更新 更多