Tutorial
Regex - Advance Search

Add Advance Search Functionality in our API

Add Advance Search Functionality

▶️ Problem 1 Statement

You can notice our API can handle only one search query at a time. We want to add more search functionality to our API.

For example, if I want to search for priority=urgent It will return all the tasks with priority as urgent but if I want to search for priority=urgent&status=completed It will return all the tasks with priority as urgent but not working for status as completed.

image

▶️ Solution

This was our previous solution for priority search query.

const {priority} = req.query;
   const queryObject = { };
 
   if(priority) {
        queryObject.priority = priority;
}
const myData = await Task.find(queryObject);

Do the same for status like first pass the status query and then pass the priority query.

   const {priority , status} = req.query;
   const queryObject = { };
 
   if(priority) {
        queryObject.priority = priority;
    }
 
    if(status) {
        queryObject.status = status;
    }
 
    console.log(queryObject);
 
  const myData = await Task.find(queryObject);
example

Change the image size by using the click-and-scroll function.

▶️ Problem 2 Statement

This followed very strict rules for searching. We want to add more flexibility to our search query.

▶️ Solution

We can use the regex to search for the query.

You can find more about regex here (opens in a new tab)

  • Searching for documents that contain a specific word or phrase in a string field.
  • Searching for documents that start or end with a specific pattern in a string field.
  • Searching for documents that have a string field matching a complex pattern with special characters.
  • Filtering for information in massive text files such as logs.

to use $regex, use one of the following syntax's:

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
  1. First remove the status from queryObject.status = status and add the following code.
if(status) {
        queryObject.status = { $regex: status, $options: 'i' };
    }

$options: 'i' is used to make the search case insensitive.

  1. Now add the following code for priority search query.
if(priority) {
        queryObject.priority = { $regex: priority, $options: 'i' };
    }
  • Now it will handle the case sensitive search query like priority=urgent and priority=Urgent both will return the same result.
  • Even if you don't pass complete word like priority=urg it will return the result.

image

Now I'm going to do the same for description

if(description) {
        queryObject.description = { $regex: description, $options: 'i' };
    }