Trying to get random cursor from collection - Error: Publish function can only return a Cursor or an array of Cursors

javascript, meteor, mongodb

Solution

You can return a cursor for a single random question.

Meteor.publish('randomQuestion', function (seed) {
  var q = _.sample(Questions.find().fetch());
  return Questions.find({_id: q && q._id});
});

You should also subscribe using a random seed to ensure that clients don't share the same publication. The below example requires that you `meteor add random`.

this.route('gamePage', {
 path: '/games',
 waitOn: function() {
   return Meteor.subscribe('randomQuestion', Random.id());
 }
});

You can then return that one question in a helper

Template.gamePage.question = function() {
  return Questions.findOne();
};

and provide that data as the context for your template.

<div class="question">
  {{> questionItem question}}
</div>

Problem

I am trying to publish a random question from a collection of questions. However I get an error stating: Error: Publish function can only return a Cursor or an array of Cursors. How do I change my publication below so this outputs one random question? Publications.js ``` Meteor.publish('randomQuestions', function(){ var randomInRange = function(min, max) { var random = Math.floor(Math.random() * (max - min + 1)) + min; return random; }; var q = Questions.find().fetch(); var count = q.length; var i = randomInRange(0, count); return q[i] }); ``` Router.js ``` this.route('gamePage', { path: '/games', waitOn: function() { return [ Meteor.subscribe('randomQuestions'), ]; } }); ``` Here is a helper on the client side to get the random question ``` Template.gamePage.helpers({ displayRandomQuestion: function() { return Questions.find({}); } }); ``` Lastly here is the html/css using the helper function ``` <div class="questions"> {{#each displayRandomQuestion}} {{> questionItem}} {{/each}} </div> ```

Original source