Reputation: 2426
Users share posts in my website and every post has a city and category and vote option.I have a menu on the top help users to filter posts on city, category, top voted and newest. What Im trying to do is:
I'm using Meteor & end up doing this spaghetti:
if ( Session.get('topPosts') ){
if(Session.get("selectedCity") && Session.get("selectedCategory")){
if (Session.get("selectedCity") === Cities[0] && Session.get("selectedCategory") === Categories[0]){
return Posts.find({}, {sort: {score: -1}});
}
else if (Session.get("selectedCity") === Cities[0]){
return Posts.find({ category: Session.get("selectedCategory") }, {sort: {score: -1}});
}
else if (Session.get("selectedCategory") === Categories[0]){
return Posts.find({ city: Session.get("selectedCity") }, {sort: {score: -1}});
}
return Posts.find({ city: Session.get("selectedCity"), category: Session.get("selectedCategory") }, {sort: {score: -1}});
}
..
I'm new to mongodb. I don't know if I can achieve this with a simple query or combining between multiple queries.
Upvotes: 0
Views: 118
Reputation: 563
Instead of having a different query for each search possibility, you can assemble a single set of search and sort parameters and apply them at the end.
var selector = {};
var sort = {};
if (Session.get('selectedCity') selector.city = Session.get('selectedCity');
if (Session.get('selectedCategory') selector.category = Session.get('selectedCategory');
if (Session.get('topPosts') sort = {sort: {score: -1}};
return Posts.find(selector, sort);
I'll let you work out how to do your special city option.
Upvotes: 1