Reputation: 339
I have the following document model...
{
_id: 'jr3h4h51gkjfhqd',
first_name: 'bob',
last_name: 'jones',
age: 33,
email: '[email protected]',
phone_number: '',
job: 'accountant',
title: 'mr'
}
Is there a way I can write a query so that the query will have a filter for a certain value if a filter is provided, otherwise there won't be a filter applied for that property.
If a filter isn't provided, then that filter is left out (essentially, if no filters are provided, then all documents will be returned), but if only one filter is provided, then the query should only filter the documents based on that one filter. Here is the query if 5 filters are provided.
User.find(
{
first_name: FIRST_NAME_FILTER,
last_name: LAST_NAME_FILTER,
email: EMAIL_FILTER,
job: JOB_FILTER,
title: TITLE_FILTER
}
)
Upvotes: 1
Views: 1077
Reputation: 8695
You can do this in 2 places
query={}
if(first_name_filter) query.add("first_name",first_name_filter);
if(last_name_filter) query.add("last_name",last_name_filter);
...
User.find(query);
Upvotes: 2