I've got a short search form that a user fills out. There will be multiple search queries that will go into MongoDB:
The form creates a variable called searchParams
that may look like this:
var searchParams = {
city: "Springfield",
bedrooms: 3,
bathrooms: 2
};
I then have a function that takes the searchParams as an argument and queries Mongo using it:
var searchListings = function(searchParams){
return db.MyListings.find(searchParams).fetch();
}
db.MyListings.find( {city: "Springfield", bedrooms: 3, bathrooms: 2} ).fetch();
This is all well and good for a complete searchParams
object, but if the user doesn't fill out parts of the form and the object turns out to be this:
var searchParams = {
city: "",
bedrooms: NaN,
bathrooms: 3
};
The query fails. It tries to literally search for a property with a city of "" and a bedroom of NaN.
What I want the query to be in the case of this object is just:
db.MyListings.find( {bathrooms: 3} ).fetch();
I can go through each key one by one and check for NaN conditions and "" conditions and somehow remove the key from the searchParams
object (I guess I'm like sterilizing the object?) but I was wondering if there was a more intelligent way to go about taking out the keys with invalid values?
I've got underscore
installed.
UPDATE: This project is currently using Meteor 0.9.1. Meteor uses Underscore 1.0.0, which is why the below did not work:
The following doesn't seem to be working:
searchParams = {
bathrooms: 3,
bedrooms: NaN,
city: "",
exteriorSize: NaN,
interiorSize: NaN,
price: 0
};
console.log(searchParams);
newSearchParams = _.omit(searchParams, function(val) {
return !val;
});
console.log(newSearchParams); // exactly the same as searchParams
And if I do this:
searchParams = {
bathrooms: 3,
bedrooms: NaN,
city: "",
exteriorSize: NaN,
interiorSize: NaN,
price: 0
};
console.log(searchParams);
newSearchParams = _.pick(searchParams, function(val) {
return !!val;
});
console.log(newSearchParams); // blank object