3
votes

I have a meteor publish function (in the server-side code) that returns an array of two cursors from two different collections. In each case, the cursors returned are supposed to contain documents that satisfy some query criteria, which is given as an argument for the function within Meteor.publish. The following code will make it more clear:

//server
Meteor.publish('publisher', function(userId){
return[
    posts.find({createdBy: userId}),
    accounts.find({_id: userId})
    ];
});
//client
Meteor.subscribe('publisher',Session.get('userId'));
//this code runs within a meteor method on the client
var id = Session.get('userId');
console.log(id)
var acnts = accounts.find({_id: id}).fetch();
console.log(acnts);

There is a login button that sets the session called 'userId'. The console logs the current id but the document logged to the console is always empty (though it exists).

Any help will be much appreciated. :)

1
Slightly hard to tell what's going on since the code is out of context, but this does typically happen because the subscription is not yet ready. If you put a breakpoint on the line with accounts.find() in the browser, and then let it run again after a pause, and it now works, then this is your problem. - Jesper We

1 Answers

1
votes

Put your client code that depends on the subscription in a callback.

//server
Meteor.publish('publisher', function(userId){
return[
    posts.find({createdBy: userId}),
    accounts.find({_id: userId})
    ];
});

//client
Meteor.subscribe('publisher',Session.get('userId'),function(){
    //this code runs within a meteor method on the client
    var id = Session.get('userId');
    console.log(id)
    var acnts = accounts.find({_id: id}).fetch();
    console.log(acnts);

});