【问题标题】:How to normalise user data from varying structures in Meteor?如何规范化来自 Meteor 中不同结构的用户数据?
【发布时间】:2020-05-03 16:43:46
【问题描述】:

我的 Meteor 应用程序中的用户可以“手动”或使用 accounts-facebook 包创建帐户。

如果他们手动创建了一个帐户,那么他们的电子邮件在数据库中的存储方式如下:

emails: [address: 'hi@gmail.com', verified: false]

但如果他们使用 Facebook 登录,那么它的存储方式如下:

services: {
  facebook: {
    email: "james@gmail.com"
  }
}

我有一个用户帐户页面,我需要在其中显示用户电子邮件并允许他们更改它。如何处理不同的结构?

我制作了这个 React 组件来显示用户的电子邮件。当我刚刚拥有默认的 Meteor 用户配置文件时,它可以工作,但现在我添加了 Facebook 登录,因为 props.user.emails 不存在而出现错误。

        <div className="form-primary__row">
          <label>Email:</label>
          {props.user.emails.map((item, i) => {
            return (
              <input defaultValue={item.address} key={i} name="email" />
            );
          })}
        </div>

这是我让用户更新其电子邮件的方法。当我只有 Meteors 帐户但不能使用 Facebook 时,它也可以工作。

Meteor.methods({
  'user.updateEmail'({ email }) {
    Meteor.users.update(
      { _id: Meteor.userId() },
      {
        $set: {
          'emails.0.address': email,
          'emails.0.verified': false,
        },
      },
    );
  },
});

【问题讨论】:

  • 如何以类似的结构格式存储手动电子邮件?例如。 services.manual.email 假设只能存在手动电子邮件或 fb 电子邮件,您可以根据存在的情况对逻辑进行编程,使其像两者中的任何一个一样返回。我相信这可以在客户端代码上进行规范化并作为标准对象发送回客户端,这样客户端就不必担心它收到的对象的结构。
  • 你能在发布函数中标准化吗?如果我在客户端组件(例如我的帐户页面)中进行规范化,那么我可能需要在另一个页面上执行相同操作,这违反了 DRY 原则。
  • 好的,我想你可以使用Accounts.onCreateUser()。创建新用户时(无论是手动还是通过 fb),拉取相应的电子邮件并填充 emails 数组。这样,您就不必接触您的出版物或客户端渲染

标签: meteor


【解决方案1】:

一种方法是使用Accounts.onCreated()

该函数应返回用户文档(传入的任一 或新创建的对象)进行任何修改。 返回的文档直接插入到 Meteor.users 收藏。

Accounts.onCreateUser(function (options, user) {
    // if the account is created using the manual approach,
    // simply return the user object that will be inserted into
    // the Users collection.
    if (!user.services.facebook) {
        return user;
    }

    // if user is created using fb's API,
    // manually set the emails array, then return the user object
    // which will be inserted into the Users collection.
    user.username = user.services.facebook.name;
    user.emails = [{address: user.services.facebook.email}];

    return user;
});

以上内容确保emails 数组始终包含电子邮件,无论用户选择使用哪种登录方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2017-10-05
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    相关资源
    最近更新 更多