Collection Sample :
{
"_id":"5f8576462680760017f64c96",
"projectType": "public",
"status": "open", //status can be open , ongoing or completed
"budget": 1000,
"revisionStatus": false,
"projectName": "Adonis industry",
"licenseType": "cs",
"location": "Algeria",
"description": "lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum",
"createdAt": "2020-08-13T09:41:26.391Z",
"updatedAt": "2020-10-13T09:41:26.391Z"
UI has 5 filters :
{"location": "xyz"}
Location
.{"datePosted" : {"startDate" : "2020-10-11" , "endDate" : "2020-10- 09}}
Date Posted
Date Posted
These filters can be applied in any combination and there is also a use case where no filters are applied at all in which case the whole collection will be fetched.
I do not want to use much IF-ElSEIF-ELSE
because there are a lot of combinations that need to be checked . I know about Queries
in mongoose but I do know how its gonna work with objects in the picture (since its a range of values) and not just a single value.
I want to know an efficient way of approaching such kind of problems and make a concise well executed API.
After all, you need to check somewhere in the code if conditions are true. So is mandatory, at least five if
conditions.
So, I think a clear and simple solution could be something like this.
With this you can use Query
and concatenate where()
clauses, so it's very easy to read.
let query = model.find()
if (location) {
query.where('location', 'Algeria')
}
if (licenseType) {
query.where('licenseType', 'cs')
}
if (datePost) {
query.where('createdAt').gte('2020-08-12').lte('2020-09-12')
}
if (dateCompleted) {
query.where('status', 'completed')
if(!datePost) query.where('createdAt').gte('2020-08-12').lte('2020-09-12')
}
if (projectBudget) {
query.where('budget', 200)
}
query.exec().then(result => {
//...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.