[英]How to Meteor.js random pickup data?
I tried to pick up data with random some like below but it seem picked up only a first one in database. 我试图随机抽取数据,如下所示,但它似乎只抽取了数据库中的第一个数据。
Template.miniSudoku.helpers({
playGame: function(){
var result = MiniSudoku.find({},{random:{$gte:Math.random()},limit:1});
if (result === null) {
var result = MiniSudoku.find({},{random:{$lte:Math.random()},limit:1});
}
return result;
}
});
You have to use random
as a selector, not as an option in the query, eg: 您必须使用
random
作为选择器,而不是查询中的选项,例如:
MiniSudoku.find({random: {$gte: Math.random()}}, {limit: 1});
Extra tips: 额外提示:
You could also rewrite this to MiniSudoku.findOne({random: {$gte: Math.random()}});
您也可以将其重写为
MiniSudoku.findOne({random: {$gte: Math.random()}});
You shouldn't use var
keyword when you assign a value second time. 第二次分配值时,请勿使用
var
关键字。
You should assign Math.random()
value to a variable, because in a corner case you can also get nothing from the second query :) 您应该将
Math.random()
值分配给变量,因为在特殊情况下,您从第二个查询中也无法获得任何结果:)
Selecting random document from Mongo can be tricky, as they don't support this out of the box like other databases do. 从Mongo中选择随机文档可能很棘手,因为它们不像其他数据库那样直接支持。 You can vote for it at https://jira.mongodb.org/browse/SERVER-533
您可以在https://jira.mongodb.org/browse/SERVER-533上为其投票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.