In my router for a post request, I parse the search parameters and then use a db find using the parameters. However, the user can choose to mix and match which parameters (title/tags) he wants to use/doesn't want to use, so it ends up that I have to search for a couple different things, thus there's a couple conditionals which determine the search as shown below.
router.post('/eventItems/:title', function(req, res) {
psuedocode for setting up booleans
HERE IS WHERE MULTIPLE CONDITIONALS ARE USED TO DETERMINE WHICH SEARCH
if (tagsShouldBeSearched && searchTitle)
{
eventItem.find({title: searchTitle, tags: tags}, function(err, data) {
var jsondata = JSON.stringify(data);
res.render('eventItems', {events : jsondata, loggedIn: isLoggedIn, matching_events: data, user : req.user });
});
}
else if (tagsShouldBeSearched)
{
eventItem.find({tags: tags}, function(err, data) {
var jsondata = JSON.stringify(data);
res.render('eventItems', {events : jsondata, loggedIn: isLoggedIn, matching_events: data, user : req.user });
});
}
else
{
eventItem.find({title: searchTitle}, function(err, data) {
var jsondata = JSON.stringify(data);
res.render('eventItems', {events : jsondata, loggedIn: isLoggedIn, matching_events: data, user : req.user });
});
}
});
Is there a better way to go about doing so without using so many conditionals? I also thought of using a lost of different router addresses for posting, but maybe that's too much?
Thanks!
You can build your query up using Mongoose's where
var Query = eventItem.find();
if (tagsShouldBeSearched) Query.where({tags: tags});
if (titleShouldBeSearched) Query.where({title: searchTitle});
Query.exec(function(err, data) {
var jsondata = JSON.stringify(data);
res.render('eventItems', {events : jsondata, loggedIn: isLoggedIn, matching_events: data, user : req.user });
});