Trying to get a random cursor from a collection - Error: the publish function can only return a cursor or an array of cursors

I am trying to post a random question from a set of questions. However, I get the error message: Error: the publish function can only return a cursor or an array of cursors. How to change my post below to bring up 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 client side helper to get a random question

Template.gamePage.helpers({
    displayRandomQuestion:
        function() {
            return Questions.find({});
        }
});

Finally, here is html / css using helper function

<div class="questions">
    {{#each displayRandomQuestion}}
      {{> questionItem}}
    {{/each}}
</div>
+4
source share
1 answer

You can return the cursor for one random question.

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

, , , . meteor add random.

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

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

.

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

Source: https://habr.com/ru/post/1548090/


All Articles