Meteor.users returns empty set when used in Meteor.publish

Okay, the last question as to why the publish function didn’t fire was due to stupidity. However, I just hit the next snag and this one is weird, because the code is pretty similar to what the tutorials state.

UserData = new Mongo.Collection("userData");
Test = new Mongo.Collection("test");

if(Meteor.isServer) {
    Meteor.publish("userData", function() {
        return Meteor.users.find({_id: this.userId});
    Meteor.publish("test", function(){
        return Test.find({});

So, here’s the thing: If I subscribe to the Test collection, I can insert(), find(), whatever I want. It finds the expected documents and inserts/deletes/updates them as it should.

The UserData collection? Not so much.

The server console actually spits out the correct amount of users - so, the Meteor.users.find().fetch() methods works as it should serverside.

Clientside Meteor.users.find().fetch() also returns what it should - namely the current user.

However, UserData.find().fetch returns [] - an empty set.

So, what am I missing now?

As answered in your other thread - your collection “allusers” has nothing to do with your publication that you also call “allusers”. When you publish, you do not publish to anything, you just make available.

So when you publish the Meteor.Users collection you must subscribe on it to access the data.

After that you can do Meteor.users.find() and get all your records.
However - your collection UserData will still be empty and happily oblivious about what’s going on with the Meteor.Users collection

What you are doing now is publishing Meteor.users and later you query UserData, which is never published and probably empty.

Ah, thank you for that explanation.

Before falling into the next trap, I would suggest you to watch the end of mentor session #4 where @serkandurusoy talks about merge-box and publications or at least read the end of this summary.
In Meteor world there’s sth. called mergebox which merges publications/subscriptions on the client. This gets especially tricky at the user collection because it automagically publishes the current user.

1 Like