Search code examples
javascriptfacebookmeteoriron-routeruser-profile

Getting Facebook Avatar in Meteor when Autopublish is removed


Currently when auto publish is removed, only {{currentUser.profile.name}} works.I'm trying to get {{currentUser.profile.first_name}} and the avatar from Facebook but have not been able to do so. Here is my code...

On the Server side:

 Meteor.publish('userData', function() {
        if(!this.userId) return null;
        return Meteor.users.find(this.userId, {fields: {
            'services.facebook': 1
        }});
    });

On Iron Router:

Router.configure({
    waitOn: function() {
        return Meteor.subscribe('userData');
    }   
 });

From my understanding, I see that Meteor is publishing all the userData and then subscribing to it via Iron Router. What I don't understand is why this is not working -- as I think {{currentUser.profile.first_name}} should work but isn't.


Solution

  • Like Richard suggests, when a user is created, you can copy the services document to the profile doc.

    Accounts.onCreateUser(function(options, user) {
        // We still want the default hook's 'profile' behavior.
        if (options.profile) {
            user.profile = options.profile;
            user.profile.memberSince = new Date();
    
            // Copy data from Facebook to user object
            user.profile.facebookId = user.services.facebook.id;
            user.profile.firstName = user.services.facebook.first_name;
            user.profile.email = user.services.facebook.email;
            user.profile.link = user.services.facebook.link;
        }
    
        return user;
    });
    

    Your publication to get their first name and Facebook ID would look like this...

    /* ============== Single User Data =============== */
    Meteor.publish('singleUser', function(id) {
        check(id, String);
    
        return Meteor.users.find(id,
            {fields: {'profile.facebookId': 1, 'profile.name': 1, 'profile.firstName': 1, 'profile.link': 1}});
    });
    

    You can access a user's Facebook avatar with a template helper function...

    Template.profileView.helpers({
        userPicHelper: function() {
            if (this.profile) {
                var id = this.profile.facebookId;
                var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
                return img;
            }
        }
    });
    

    In your template, you can then use the following helper (provided you are wrapping this in a block that contains user data):

    <img src="{{userPicHelper}}" alt="" />