Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making subscriptions with arguments in meteor

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. :)

like image 322
Ajmal Avatar asked Nov 17 '25 15:11

Ajmal


1 Answers

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);

});
like image 79
cobberboy Avatar answered Nov 19 '25 09:11

cobberboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!