试图从集合中获取随机游标 - 错误:发布函数只能返回Cursor或Cursors数组 [英] Trying to get random cursor from collection - Error: Publish function can only return a Cursor or an array of Cursors

查看:129
本文介绍了试图从集合中获取随机游标 - 错误:发布函数只能返回Cursor或Cursors数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一系列问题中发布随机问题。但是我得到一个错误说明:错误:发布功能只能返回Cursor或Cursors数组。如何在下面更改我的出版物,以便输出一个随机问题?

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

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

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({});
        }
});

最后这里是使用帮助函数的html / css

Lastly here is the html/css using the helper function

<div class="questions">
    {{#each displayRandomQuestion}}
      {{> questionItem}}
    {{/each}}
</div>


推荐答案

您可以为单个随机问题返回光标。

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});
});

您还应使用随机种子进行订阅,以确保客户端不共享同一发布。以下示例要求您 meteor add random

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>

这篇关于试图从集合中获取随机游标 - 错误:发布函数只能返回Cursor或Cursors数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆