Reputation: 33
I am trying to build a basic property listing website. This website has the following filters:
Both of these filters are completely optional. You can use both together, individually, or not at all. For example, the user could specify 1 bedroom and leave the number of bathrooms blank. This would return all listings with 1 bedroom and any number of bathrooms.
I am trying to implement the above scenario using MongooseJs. My Schema is defined as follows:
var listing = new Schema({
bathrooms: Number,
bedrooms: Number,
});
When the user uses the filter, the following code is used on my Node, Express server:
var bedrooms = req.param('bedrooms');
var bathrooms = req.param('bathrooms');
Listing.find({
bedrooms: bedrooms,
bathrooms: bathrooms
}, function(err, filterdListings) {
res.render('listings', {
title: 'Listings',
listings: filterdListings
});
})
Here is where my problem comes in, my variables: bedrooms and bathrooms above, could be left blank. This results in Mongoose trying to search for entries in the database where these variables are assigned to ''.
Could you please point me in the right direction so that I can achieve the desired behaviour if one of these filter values is left blank?
Upvotes: 1
Views: 2508
Reputation: 5352
I am assuming you are using a GET request (based on req.params). I would change it to a POST request. Your route will probably look like this:
/api/filter/:bedrooms?/:bathrooms?
In your question you mentioned that both bedrooms and bathrooms can be optional. When a user filters for bathrooms but leaves bedrooms empty, the following route will be triggered:
/api/filter/3
The users filters for 3 bathrooms but your function thinks he filters for 3 bedrooms.
That being said, I would send both parameters in a POST request. Your postdata will look like this:
{
bedrooms: 3,
bathrooms: 3
}
When a user only enters 1 filter, you will only send this property. Your query itself will look like the answer from @TechImpossible.
var bedrooms = req.param('bedrooms');
var bathrooms = req.param('bathrooms');
var query = {};
if(req.body.hasOwnProperty('bedrooms')) {
query.bedrooms = req.body.bedrooms;
}
if(req.body.hasOwnProperty('bathrooms')) {
query.bathrooms = req.body.bathrooms;
}
Listing.find(query, function(err, filterdListings) {
res.render('listings', {
title: 'Listings',
listings: filterdListings
});
});
Upvotes: 1
Reputation: 126
You could try.
var bedrooms = req.param('bedrooms');
var bathrooms = req.param('bathrooms');
var myFilter = {};
if bedrooms {
myFilter.bedrooms = bedrooms;
}
if bathrooms {
myFilter.bathrooms = bathrooms;
}
Listing.find( myFilter, function(err, filterdListings) {
res.render('listings', {
title: 'Listings',
listings: filterdListings
});
})
I could not test in, so it comes as is without warranty ;)
Upvotes: 2