I am currently working on implementing filters for a mongo find query. The objective is to have the mongo selector limit the retrieved data based on the specified filters. However, if no filter is provided (the filter has a null or default value), then the query should return all documents without any limitations. I have successfully implemented the filter functionality for when filters are specified, but I am facing difficulty in ensuring that unfiltered results are returned when no filters are specified. How can I modify the find query to retrieve all documents in the collection when the filters are unspecified or at their default values?
Just so you know: I am incorporating this into a Meteor project and will be turning the filters into Session variables to achieve dynamic result retrieval.
Example Collection:
/* example documents in SampleCollection
{ name: "sample1", fieldA: "foo", fieldB: "foo" }
{ name: "sample2", fieldA: "foo", fieldB: "bar" }
{ name: "sample3", fieldA: "bar", fieldB: "foo" }
{ name: "sample4", fieldA: "bar", fieldB: "bar" }
*/
Example JS Code:
var filters = {
fieldA: null,
fieldB: null
};
var getFieldASelector = function () {
if (filters.fieldA) {
return { $eq: fieldA };
} else {
/* fieldA has a falsey value which is the default
and therefore should not limit the find query */
// unsure of what to return here
return {};
};
};
var getFieldBSelector = function () {
if (filters.fieldB) {
return { $eq: fieldB };
} else {
/* fieldB has a falsey value which is the default
and therefore should not limit the find query */
// unsure of what to return here
return {};
};
};
var results = SampleCollection.find({
fieldA: getFieldASelector(),
fieldB: getFieldBSelector()
});
In this scenario, results
should ideally fetch all four documents. However, if
filter = { fieldA: "foo", fieldB: null };
is applied, then results
should only return sample1 and sample2.