Accounts.onCreateUser 清理我的代码

Accounts.onCreateUser clean up my code

创建新用户帐户后,我使用 Accounts.onCreateUser 函数将数据插入新集合。我想在进行之前检查插入是否成功。我的代码似乎可以工作,但看起来很乱。我想知道是否有更简洁的方法来编写这段代码。

Accounts.onCreateUser((options, user) => {
  if (user) {
    CandidateProfile.insert({
      userId: user._id,
      firstName: options.profile.name.first,
      lastName: options.profile.name.last
    });

    var checkForNewCandidateProfile = CandidateProfile.findOne(
      { userId: user._id },
      { fields: { userId: 1 } }
    );
    var userId =
      checkForNewCandidateProfile && checkForNewCandidateProfile.userId;

    if (userId === user._id) {
      return user;
    }
  }
});

就个人而言,我认为您的测试没有任何意义。你不信任 insert?

但是好的,你需要它。

  1. 确保您 运行 服务器端的代码。仅在服务器端导入它或将其包装在 if (Meteor.isServer)

  2. 为什么要检查 user arg 是否存在?是的,这就是回调的工作方式。

  3. 如果出现问题,抛出错误以中止用户创建。

可能的变体:

if (Meteor.isServer) {
  Accounts.onCreateUser((options, user) => {
    // You insert sync, so it's up to you to handle errors.
    try {
      CandidateProfile.insert({
        userId: user._id,
        firstName: options.profile.name.first,
        lastName: options.profile.name.last
      });

      var checkForNewCandidateProfile = CandidateProfile.findOne(
        { userId: user._id },
        { fields: { userId: 1 } }
      );
      var userId =
        checkForNewCandidateProfile && checkForNewCandidateProfile.userId;

      if (userId === user._id) {
        return user;
      }
    } catch (error) {
      throw new Error(error);
    }
    throw new Error("Something's wrong.");
  });
}