Reputation: 690
I need to access collection on client-side javascript files to sort data and perform various operations. Currently I'm just using find()
or findOne()
, but it's very inconsistent and sometimes doesn't return value quickly enough so it doesn't work.
Am I doing it the right way? Are there any other options provided to retrieve and manipulate collection data?
For example, I want to find this data:
data = Stats.findOne({
name: Session.get('name')
}, {sort: {date: -1}});
variable = data.variable;
And then I want to use variable
to filter collection:
ranking = Stats.find({
variable: variable
}, {sort: {score: -1}}).fetch();
I can't find a reason why it doesn't work.
Upvotes: 0
Views: 575
Reputation: 4049
Meteor is reactive, which means that as that Stats collection populates with data from the server, code that uses it will be automatically re-run. If you're trying to display the data
on screen, you want to use a helper, a reactive variable, and the autorun function.
JS:
Template.yourTemplate.onCreated( function() {
var template = this;
template.variable = new ReactiveVar( null );
template.autorun( function() {
var result = Stats.findOne({ name: Session.get('name') }, { sort: { date: -1 } });
if( result && result.variable ) {
template.variable.set( result.variable );
}
});
});
Template.yourTemplate.helpers({
ranking() {
return Stats.find({ variable: Template.instance().variable.get() }, { sort: { score: -1 } }).fetch();
}
});
HTML:
<template name="yourTemplate">
{{#each rank in ranking}}
Do stuff with {{rank}}
{{/each}}
</template>
This will ensure that your reactive variable changes as Stats.findOne()
of your session variable changes, and that your template can appropriately get the rankings you want.
Upvotes: 1