0

I am trying to get the value of a field from a document returned via a subscription. The subscription is placed inside a helper function. I had a callback function within the subscription return this value and then I assigned the return value to a variable (see code). Finally, I had the helper return this value. However, the value returned is a subscription object (?) and I can't seem to get anything out of it.

Code:

Template.myTemplate.helpers({
    'returnUser':function(){
        var id = Session.get('currentUserId');
        var xyz = Meteor.subscribe('subscriptionName',id,function(){
            var user = accounts.find().fetch({_id: id})[0].username; 
            return user;
            }
        return xyz;
        }
});

Any help will be much appreciated. :)

Ajmal
  • 87
  • 9

1 Answers1

2

You have to load first your subscriptions when the template is created, this creates an instance of your data with Minimongo.

Template.myTemplate.onCreated(function () {
    var self = this;
    self.autorun(function() {
        self.subscribe('subscriptionName',id);
    });
});

Then in the helper, you can make a query to retrieve your data

Template.myTemplate.helpers({
    'returnUser': function(){
        var id = Session.get('currentUserId');
        return accounts.findOne(id).username;
    }
});
Michel Floyd
  • 16,271
  • 4
  • 21
  • 38
alexhenkel
  • 472
  • 2
  • 8
  • What is the purpose of assigning this to self? Wouldn't it work fine with using this.autorun and this.subscribe? – Ajmal Nov 09 '16 at 18:51