import './Products.html'; Tracker.autorun(function() { Meteor.subscribe("products"); Meteor.subscribe("productTags"); }); Template.Products.helpers({ products: function() { let query = Session.get('searchQuery'); let dbQuery = {}; if(query) { _.each(_.keys(query), function(key) { if(_.isFunction(query[key])) dbQuery[key] = query[key](); else if(_.isObject(query[key])) dbQuery[key] = query[key]; else if(_.isNumber(query[key])) dbQuery[key] = query[key]; else dbQuery[key] = {$regex: query[key], $options: 'i'}; }) } return Meteor.collections.Products.find(dbQuery, {limit: 20, sort: {name: 1}}); } }); Template.ProductSearch.events({ "keyup .searchInput": _.throttle(function(event, template) { let searchQuery = Session.get('searchQuery') || {}; let searchFields = Session.get('searchFields') || {}; let searchValue = template.$('.searchInput').val(); if(searchValue) { if(this.number) searchValue = parseFloat(searchValue); if(this.collection) { let ids = Meteor.collections[this.collection].find({[this.collectionQueryColumnName]: {$regex: searchValue, $options: 'i'}}, {fields: {[this.collectionResultColumnName]: 1}}).fetch(); //Convert the ids to an array of ids instead of an array of objects containing an id. for(let i = 0; i < ids.length; i++) {ids[i] = ids[i]._id;} searchQuery[this.columnName] = {$in: ids}; searchFields[this.columnName] = searchValue; } else { searchFields[this.columnName] = searchQuery[this.columnName] = searchValue; } } else { //Remove columns from the search query whose values are empty so we don't bother the database with them. delete searchQuery[this.columnName]; delete searchFields[this.columnName]; } Session.set('searchQuery', searchQuery); }, 500) }); Template.ProductSearch.helpers({ searchValue: function() { let searchFields = Session.get('searchFields'); return (searchFields && searchFields[this.columnName]) ? searchFields[this.columnName] : ''; } }); Template.Product.helpers({ measures: function() { let result = ""; if(this.measures && this.measures.length > 0) { let measureNames = []; for(let i = 0; i < this.measures.length; i++) { let measureObject = Meteor.collections.Measures.findOne(this.measures[i]); if(measureObject && measureObject.name) measureNames.push(measureObject.name); } result = measureNames.join(", "); } return result; }, tags: function() { let result = ""; if(this.tags && this.tags.length > 0) { let tagNames = []; for(let i = 0; i < this.tags.length; i++) { let obj = Meteor.collections.ProductTags.findOne(this.tags[i]); if(obj && obj.name) tagNames.push(obj.name); } result = tagNames.join(", "); } return result; } });