Add Advance Search Functionality in our API
▶️ Problem Statement
Suppose if you want to sort the task according to the priority of the task or status of the task or dueDate of the task then how will you do it?
▶️ Solution
In mongoose we can sort the data using sort() method.
Read the documentation of mongoose sort() method here (opens in a new tab)
You can use any of the following methods to sort the data.
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
// equivalent
query.sort('field -test');
// also possible is to use a array with array key-value pairs
query.sort([['field', 'asc']]);
- First one : sort by "field" ascending/ descending and "test" -1 means descending and 1 means ascending
- Second one : sort by "field" ascending/ descending and "test" -1 means descending and 1 means ascending
- Third one : array with array key-value pairs
- We will use the second method to sort the data.
First we will try it on our testing server and then we will implement it on our production server.
- We will try it for dueDate field if you want to sort the date according to the ascending order then you can use
sort('dueDate')
and if you want to sort the date according to the descending order then you can usesort('-dueDate')
.
Ascending order
const getAllTasksTesting = async (req, res) => {
const myData = await Task.find(req.query).sort('dueDate');
res.status(200).json({ myData });
};
Descending order
const getAllTasksTesting = async (req, res) => {
const myData = await Task.find(req.query).sort('-dueDate');
res.status(200).json({ myData });
};
▶️ Problem Statement
Now if you want to sort the data according to the priority of the task then how will you do it?
For example if someone try to do http://localhost:5000/api/tasks/testing?sort=createdAt
then it will return the sorted data according to dueDate
field because we have already sorted the data according to the dueDate
field.
But I want if someone try to do http://localhost:5000/api/tasks/testing?sort=createdAt
then it will return the sorted data according to createdAt
field.
▶️ Solution
const { priority, status, description, sort } = req.query;
if (sort) {
let sortProblem = sort.replace(",", " ");
queryObject.sort = sortProblem;
}
const myData = await Task.find(queryObject).sort('sort');
But this will not work because always we will get the same sorted data .
So we want to sort the data when user will pass the sort
query parameter.
So we will use the if
statement to check if the user has passed the sort
query parameter or not.
- We can do first something like this.
let apiData =Task.find(queryObject);
const myData = await apiData.sort('sort');
- Now if user write
sort
then it will return the sorted data according tosort
field.
- So remove the
queryObject.sort = sortProblem;
and writeapiData = apiData.sort(sortProblem);
and it will work.
const { priority, status, description, sort } = req.query;
if (sort) {
let sortProblem = sort.replace(",", " ");
apiData = apiData.sort(sortProblem);
}
const myData = await apiData;
Now you can see it will not return by default the sorted data.
- Entire code
const Task = require("../models/Task");
const getAllTasks = async (req, res) => {
const { priority, status, description, sort } = req.query;
const queryObject = {};
if (priority) {
queryObject.priority = { $regex: priority, $options: "i" };
}
if (status) {
queryObject.status = { $regex: status, $options: "i" };
}
if (description) {
queryObject.description = { $regex: description, $options: "i" };
}
let apiData = Task.find(queryObject);
if (sort) {
let sortProblem = sort.replace(",", " ");
apiData = apiData.sort(sortProblem);
}
console.log(queryObject);
const myData = await apiData;
res.status(200).json({ myData });
};
Now you can see after passing the
sort
query parameter it will return the sorted data even you can sort the data according to multiple fields.
⚡ Check this with URL
http://localhost:5000/api/tasks?sort=dueDate
http://localhost:5000/api/tasks?sort=dueDate,createdAt
http://localhost:5000/api/tasks?sort=dueDate,createdAt,-priority
▶️ Conclusion
We have learned how to sort the data according to the query parameter.