Reputation: 143
I'm building a Meteor app where I have a collection with products. Each document in that collection has two fields: productName and productCategory. In my app I want to show all products for a given category. So I have a select field where I want to select a category. After pushing the search button I want to show a list with all products for the given category.
In my template I have the following code to create the select field
<select>
{{#each distinct_products}}
<option>{{productCategory}}</option>
{{/each}}
<select>
In my js file, the definition of distinct_product is as follow:
Template.templatename.distinct_products = function() {
var distinctEntries = _.uniq(Meteor.products.find({}, {sort: {productCategory:1}, fields: {productCategory:true}}).fetch().map(function(x) {
return x.productCategory;
}), true);
return distinctEntries;
};
I found this solution in the following topic: Meteor: how to search for only distinct field values aka a collection.distinct("fieldname") similar to Mongo's
However, My select field shows a number of options equal as the number of unique product categories, but it are empty values (no text). Thus, my select fields has a number of empty options and no product category is showed.
I suppose there is something wrong with the type of the returned value in my JS function, but I don't know what. Can someone put me on the right path please.
Thanks.
Upvotes: 0
Views: 2644
Reputation: 1964
I was able to shorten it
var wow = _.uniq(_.pluck(Nodes.find().fetch(),"productCategory"));
Upvotes: 0
Reputation: 8013
Your _.uniq
block will return an array of productCategory
properties, which is what your{{#each}
block is iterating over - so you shouldn't be specifying {{productCategory}}
again in your template.
Change this:
<option>{{productCategory}}</option>
to:
<option>{{this}}</option>
and it should work. By trying to access {{productCategory}}
within the loop, you are in effect asking for product.productCategory.productCategory
, which is going to be empty; product.productCategory
is already being returned by your helper.
As a side note, _.pluck
is designed as a more concise version what you're using _.map
for, so it might be worth checking out.
Upvotes: 2