user1952811
user1952811

Reputation: 2458

Meteor MongoDB find / fetch issues

Meteor.publish('polls', function () { 
    return Polls.find({}); 
});

Meteor.publish('recentPolls', function() {
    return Polls.find({}, {sort: {date: -1}, limit: 10}).fetch();
});

So this is in my /server/server.js file from the documentation it says the fetch() method returns matched documents in an array. However, using the subscribe function in the client like so

Template.recentPolls.polls = function() {
    console.log(Meteor.subscribe('recentPolls'));
    return Meteor.subscribe('recentPolls');
}

For some odd reason this is returning the following object (not an array) but an object

Object {stop: function, ready: function}

And this is the error I get in the console.

Exception from sub 5NozeQwianv2DL2eo Error: Publish function returned an array of non-Cursors

Upvotes: 2

Views: 5528

Answers (1)

David Weldon
David Weldon

Reputation: 64312

fetch returns an array of objects, which isn't a legal value to return from a publish function.

Publish functions can only return a cursor, an array of cursors, or a falsy value. To fix your error, just remove the fetch:

return Polls.find({}, {sort: {date: -1}, limit: 10});

On the client you do not want to subscribe inside of your templates. You want to either subscribe once (usually in a file called client/subscriptions.js) or inside of your route (see the iron-router documentation).

Ignore whatever the subscribe returns. Calling subscribe just allows the server to sync data to the client. The result of the call is not the data itself.

To access your data from your template, just use another find like:

Template.recentPolls.polls = function() {
  Polls.find({}, {sort: {date: -1}});
}

Upvotes: 4

Related Questions