Accounts.onCreateUser清理我的代码

时间:2017-04-23 23:53:43

标签: meteor meteor-accounts

创建新用户帐户时,我使用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;
    }
  }
});

1 个答案:

答案 0 :(得分:0)

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

但是,你需要它。

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

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

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

  4. 可能的变体:

    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.");
      });
    }
    
相关问题