【问题标题】:Meteor onCreateUser issue流星 onCreateUser 问题
【发布时间】:2013-04-12 00:31:53
【问题描述】:

我正在使用 Meteor,人们可以通过 Facebook 连接到该网站。我正在使用人员用户名来识别他们。但是,其中一些没有用户名。例如,新用户的用户名为 null。我想做的是,如果这个人有用户名,那么我们使用他们的用户名。如果没有,我想用他们的 Facebook id 作为他们的用户名。问题是,我的 if 条件无法正常工作。如果此人有用户名,则 if 条件认为此人没有。奇怪的是,如果我在 if 条件之前执行用户名的 console.log,它将显示用户名。但是一旦在if中,它认为用户名是空的。这是代码:

Accounts.onCreateUser(function(options, user) {
  var fb = user.services.facebook;
  var token = user.services.facebook.accessToken;

    if (options.profile) { 

        options.profile.fb_id = fb.id;
        options.profile.gender = fb.gender;
        options.profile.username = fb.username    

        console.log( 'username : ' + options.profile.username); 


        if ( !(options.profile.username === null || options.profile.username ==="null" || options.profile.username === undefined || options.profile.username === "undefined")) {
          console.log('noooooooo');
          options.profile.username = fb.id; 
        } else {
          console.log('yessssssss');
          options.profile.username = fb.username;
        }

        options.profile.email = fb.email; 
        options.profile.firstname = fb.first_name;

        user.profile = options.profile;     
    }


    sendWelcomeEmail(options.profile.name, options.profile.email); 
    return user;
}); 

使用此代码,如果我使用具有用户名的 Facebook 登录。条件将显示 'noooooooo' 但 console.log('username : ' + options.profile.username);将显示我的用户名。为什么这样做? :l

【问题讨论】:

  • if 语句中的条件被 ! 否定。为此运行输入和输出:假设用户名是“brad”。那么条件中的options.profile.username 将不等于null,或“null”,或未定义,或“未定义”,因此内部条件将返回false。但是,它随后被! 否定,因此您的条件将(至少大部分)以与您想要的相反的方式运行。
  • 我还建议更改内部条件。在 JavaScript 中检查变量是否存在的一种标准方法是通过typeof options.profile.username !== "undefined"。我认为这可能符合您的目的。
  • 谢谢你!那行得通:)

标签: meteor


【解决方案1】:

这是因为创建是在记录之前调用的,并且记录是异步的..所以你不能确保你的 if 将是或不会是真/假。您从 fb 服务中输入的信息是多余的,因为所有这些信息都已与用户一起保存。

http://docs.meteor.com/#meteor_user

您应该在用户登录后获取有关用户的信息,因为在那一刻您将能够识别出您可以使用什么样的标识符。用户名/id。

//Server side
Meteor.publish("userData", function () {
    return Meteor.users.find({_id: this.userId});

    // You can publish only facebook id..
    /*return Meteor.users.find({_id: this.userId},
        {
            fields: {
                'services.facebook.id': true
            }
        }
    );*/
});

//Client side
Meteor.subscribe("userData");

// .. you can see more informations about logged user
console.log(Meteor.users.find({}).fetch());

【讨论】:

  • 这正是我在服务器端和客户端所拥有的。但它不起作用。
  • 你可以创建例如要点并给我链接,我可以为您提供更多帮助。
  • 我的问题略有不同,但在尝试其他想法近 8 小时后,这个问题终于奏效了。直到我开始我的问题,我才找到它。谢谢@JanRudovsky
猜你喜欢
  • 2013-12-05
  • 2019-10-03
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多