简体   繁体   中英

filtering documents in mongodb using node js

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: This filter is to get all the projects on the basis of a location. It will be a single value in the request body. Format eg - {"location": "xyz"}
  • LicenseType: This filter is to get all the projects on the basis of licenseType. Similar to Location .
  • Date Posted: This filter is to get the projects posted within a certain date range. It is going to an object in the request body. Format eg - {"datePosted" : {"startDate" : "2020-10-11" , "endDate" : "2020-10- 09}}
  • Date Completed: This filter is to get all the projects within a certain date range and have the status as completed. Format is again the same as Date Posted
  • Project budget: This filter is to get all the projects within a certain budget range. Format is again similar to 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM