0

I have the following code:

import { Meteor } from 'meteor/meteor';
import { Items } from './collection';

    if (Meteor.isServer) {
      Meteor.publish('items', function(options, owner) {

        let selector = {
          $and: [{ ownerId: owner}]
        }

        return Items.find(selector, options);

      });
    }

And on the client side I have:

this.subscribe('items', () => [{
      limit: this.getReactively('querylimit'),
      sort: {dateTime: -1}
    },
    this.getReactively('ownerId')
    ]);

The above does not return any results. However, when I change the return statement to the following, it works!

return Items.find({ ownerId: '7QcWm55wGw69hpuy2' }, options); //works !!!

I'm not very familiar with Mongo/Meteor query selectors. Passing the query as a variable to Items.find() seems to be messing something up. Can someone please help me figure this out!

Thanks

Neo
  • 5
  • 2

1 Answers1

0

You are trying to pass a function as the selector, which won't work. Functions can't be serialized and sent from the client to the server. Instead you need to evaluate the options and the owner separately. Here's an example:

var owner = this.getReactively('ownerId');
var options = {
  limit: this.getReactively('querylimit'),
  sort: {dateTime: -1}
};

this.subscribe('items', options, owner);

Note that the published documents will not arrive in sorted order, so unless you are using a limit, the sort doesn't help here.

Also note that if you need the subscription to rerun after the owner or query limit change, you'll need to subscribe inside of an autorun.

Here's a start on an improved implementation:

Meteor.publish('items', function(options, owner) {
  // DANGER! Actually check this against something safe!
  check(options, Object);

  // DANGER! Should any user subscribe for any owner's items?
  check(owner, Match.Maybe(String));

  // Publish the current user's items by default.
  if (!owner) {
    owner = this.userId;
  }

  return Items.find({ ownerId: owner }, options);
});
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Thanks. I'm on mobile at the moment so I can't check for now. However, I wonder why I was able to use console.log on server side to print the arguments. console.log(selector) prints the ownerId string that I've pasted in the second return statement. – Neo Jun 27 '16 at 18:43
  • Thanks again, however this does't seem to solve the issue – Neo Jun 28 '16 at 05:18
  • What do you get when you `console.log` the arguments to the `publish` function? Did you put the `subscribe` in an `autorun`? – David Weldon Jun 28 '16 at 06:21
  • Oops! Forgive me, my bad. While changing everything I had code moved out from the callback function of the subscription. It works as expected now! Thanks a lot for your help! – Neo Jun 28 '16 at 07:41