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

a 夏天 提交于 2019-12-23 13:12:08

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/24702110/trying-to-get-random-cursor-from-collection-error-publish-function-can-only-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!