I am trying to make a search system for my Next JS API. This API stores some data like fuel prices and fuel station name, etc. Below is the code:
class ApiFeatures {
constructor(query, queryStr) {
this.query = query;
this.queryStr = queryStr;
}
search() {
const keyword = this.queryStr.keyword
? {
$or: [ //Causing the issue
{
name: {
$regex: this.queryStr.keyword,
$options: "i",
},
},
{
email: {
$regex: this.queryStr.keyword,
$options: "i",
},
},
{
//I think this is causing issue. Please read down below for more details.
petrolPumpName: {
$regex: this.queryStr.keyword,
$options: "i",
},
},
],
}
: {};
this.query = this.query.find({ ...keyword });
return this;
}
API function of Next JS.
const handler = catchAsyncErrors(async (req, res) => {
const apiFeature = new ApiFeatures(
//\/ this function is called without searching
User.find().select("-role -verified"),
req.query
// \/ calling the search function
).search();
const users = await apiFeature.query;
if (users.length === 0) {
return res.status(404).json("No User Found");
}
return res.status(200).json(users);
});
export default connectToMongo(isAuthenticated(catchAsyncErrors(handler)));
using this function I am trying to fetch data only for the requested query. Example: If the query URL is - http://localhost.com/users?keyword=username then I want list of all the user with that particular user but instead it search for all the user like normal MongoDB find() function does.
{
"rate": 50,
"quantity": 100,
"amount": 5000,
"fuelStationName": "Abc fuel Station"
},
// Why this is below one? \/
{
"rate": 50,
"quantity": 100,
"amount": 5000,
"fuelStationName": "XYZ"
}
Inside that find method of query, you can pass the particular field with its value then it will give you only that document. For example:
User.find({name:"user name"});
it will only return you the user with that name only.