You could use the meteorhacks:aggregate package to run an aggregation. However, as @mrzafod correctly says, this will only work on the server, and the meteorhacks:aggregate
package does not provide any client functionality for you to transparently work with the results (for example in a template helper).
There are a number of ways of making this work.
For a small number of documents, you could do this without any server aggregation, by using _.uniq
in your helper:
Template.getProjects.helpers({
sites: function() {
return _.uniq(Sites.find({},{sort: {
project: 1}
}).fetch(), true, doc => {
return doc.project;
});
}
});
<template name="getProjects">
{{#each sites}}
<div>Project: {{project}}</div>
{{/each}}
</template>
However, for a large base document count, the optimum solution will depend on how much reactivity you want and how that reactivity is being driven. The suggestion below is probably one of the simplest and is minimally reactive, in that it requires you to kick the aggregation off and wait for the results. I haven’t used meteorhacks:aggregate
, because it’s easy enough to run the distinct
method on a rawCollection
(which exposes the underlying node library) and doing it this way is useful insight.
Client
Template.getProjects.onCreated(function() {
this.distinct = new ReactiveVar();
Meteor.call('getDistinct', (error, result) => {
if (error) {
// do something
} else {
this.distinct.set(result); // save result when we get it
}
});
});
Template.getProjects.helpers({
sites: function() {
const projects = Template.instance().distinct.get();
// turn our array of project values into an array of {project: project}
return _.map(projects, project => {
return {project}
});
}
});
<template name="getProjects">
{{#each sites}}
<div>Project: {{project}}</div>
{{/each}}
</template>
Server
Meteor.methods({
getDistinct: function() {
return Meteor.wrapAsync(callback => {
Sites.rawCollection().distinct('project', callback);
})();
}
});
You’ll need to meteor add reactive-var
to your app if it’s not already in.
EDIT: fixed “new” typo.