Search code examples
javascriptfacebookmeteormeteor-accounts

Get facebook information in meteor


I'm using Meteor.loginWithFacebook

The user is storing as:

{
    "_id" : "cnzMXwmvtF42Dfy4q",
    "createdAt" : ISODate("2016-08-31T15:58:00.814Z"),
    "services" : {
        "facebook" : {
            "accessToken" : "randomtoken",
            "expiresAt" : 1477842969226,
            "id" : "randomid",
            "email" : "[email protected]",
            "name" : "Name",
            "first_name" : "Firstname",
            "last_name" : "Lastname",
            "link" : "https://www.facebook.com/...",
            "gender" : "male",
            "locale" : "en_US",
            "age_range" : {
                "min" : 21
            }
        },
        "resume" : {
            "loginTokens" : [
                {
                    "when" : ISODate("2016-08-31T15:58:00.818Z"),
                    "hashedToken" : "randomtoken"
                }
            ]
        }
    },
    "profile" : {
        "name" : "Firstname"
    }
}

But when I do: console.log(Meteor.user().services);

It returns as undefined.

But if I do console.log(Meteor.user().profile); it brings the name correctly.

Question

How do I retrieve the facebook information in meteor?


Solution

  • By default, only the username, email and profile object are published to the client. You need to write a publication and subscribe to that on the client to expose the fields you need.

    That being said, it may not suit your purposes to publish the services.facebook object directly. If you're using more than one authentication method such as Google or username/password, you'll likely want to standardize your users documents by copying the information you need into different fields.

    Here is how I handle a project that uses Facebook, Google, and regular old email/password:

    Accounts.onCreateUser(function(options, user) {
        // Copy first name and last name from user services
        if (user.services.google) {
            user.firstName = user.services.google.given_name;
            user.lastName = user.services.google.family_name;
        } else if (user.services.facebook) {
            user.firstName = user.services.facebook.first_name;
            user.lastName = user.services.facebook.last_name;
        }
    
        // You can use the profile object to pass in user information in a password signup form
        if (options && options.profile) {
            if (options.profile.firstName) {
                user.firstName = options.profile.firstName;
            }
    
            if (options.profile.lastName) {
                user.lastName = options.profile.lastName;
            }
        }
    
        return user;
    });
    

    Note that it is NOT recommended that you use the profile object to store user data.