1
votes

Publish and Subscribe did not work. Please find the solution as an answer down below.

Initial question: I am trying to publish the facebook first_name which is automatically retrieved when logging in with the accounts facebook package in Meteor (stored in the user collection under services.facebook). I have autopublish and insecure removed.

What I have tried so far looks like this:

Server side

Meteor.publish("facebook_name", function() {
return Meteor.users.find({_id: this.userId}, 
  {fields: {'services.facebook.first_name' : true} });
});

Client side

Meteor.subscribe('facebook_name');

What I am using in my template to display it is this

<div class="Name"><p>{{currentUser.services.facebook.first_name}}</p></div>

Before removing autopublish the name showed up in the template.

2
Have you tried {fields: {'services.facebook.first_name' : 1}? - L4zl0w
yes I tried, didn“t change anything - Tobias Heckmann
Where is your subscription? Can you show the code? - L4zl0w
It is the first subscription I have right now. It is in client/main.js so far. - Tobias Heckmann

2 Answers

1
votes

Found the solution to my problem:

When setting up your meteor project in your client/main.js it will show import './main.html'; if you are working with routing and templates and not the main.html template this will prevent publish and subscribe to work correctly.

0
votes

When user is logged in via facebook oauth API and the authentication was implemented using meteor accounts-facebook, then all needed data is stored in current user object ( Meteor.user() ).

So, the schema of user in your case looks similar to this:

{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
  "facebook": {
    "accessToken": "XXX",
    "expiresAt": 1454970581716,
    "id": "XXX",
    "email": "[email protected]",
    "name": "Ada Lovelace",
    "first_name": "Ada",
    "last_name": "Lovelace",
    "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
    "gender": "female",
    "locale": "en_US",
    "age_range": {
      "min": 21
    }
  },
"resume": {
  "loginTokens": [
    {
      "when": "2015-12-10T22:29:46.858Z",
      "hashedToken": "XXX"
    }
  ]
 }
},
"profile": {
  "name": "Sashko Stubailo"
 }
}

Thus, if you want to retrieve a name of a user, all you need to do is to publish current user to a client and then get username from user object.

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

// client
Meteor.subscribe("userData");

Template.templateName.helpers({
 // this function returns username
 Username : function(){
 // if user is logged in using facebook; otherwise user is logged in using password
 if   (Meteor.user().profile.name)
   return Meteor.user().profile.name;
 else 
   return Meteor.user().username;
}

Now you can display a name of a user in your view: {{Username}}

Here is more info...