'Ignore undefined values in the find method
I have a service function that should return users based on condition, when it's present, or return just all records from collection:
function getUsers(status: string[]) {
return this.usersModel.find({ status });
}
But when users don't submit anything in params, the status will be undefined and mongo will search for users with status: undefined. Can I make the mongoose find function ignore status if it's undefined and do not include it in the query?
NOTE: I don't want to explicitly construct the query in the service, as it's violating the service scope of responsibility.
Solution 1:[1]
Perhaps I'm missing something here, but is there anything stopping you from simply running a different query (one absent of such conditions) if status is empty?
It is afterall a service function, business logic isn't the end of the world :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Liam Stewart |
