My ApiFeatures is work fine without the search feature when I add the keyword to the query the response is always empty array
class ApiFeatures {
constructor(mongooseQuery, queryStr) {
this.mongooseQuery = mongooseQuery;
this.queryStr = queryStr;
}
filter() {
const queryObj = { ...this.queryStr };
const excludesFields = ['page', 'sort', 'limit', 'fields'];
excludesFields.forEach(field => delete queryObj[field]);
let queryStr = JSON.stringify(queryObj);
queryStr = queryStr.replace(/b(gte|gt|lte|lt)b/g, match => `$${match}`);
this.mongooseQuery = this.mongooseQuery.find(JSON.parse(queryStr));
return this;
}
sort() {
if (this.queryStr.sort) {
const sortBy = this.queryStr.sort.split(',').join(' ');
this.mongooseQuery = this.mongooseQuery.sort(sortBy);
} else {
this.mongooseQuery = this.mongooseQuery.sort('-sold');
}
return this;
}
limitFields() {
if (this.queryStr.fields) {
const fields = this.queryStr.fields.split(',').join(' ');
this.mongooseQuery = this.mongooseQuery.select(fields);
} else {
this.mongooseQuery = this.mongooseQuery.select('-__v');
}
return this;
}
search() {
if (this.queryStr.keyword) {
const query = {};
query.$or = [
{
title: {
$regex: this.queryStr.keyword,
$options: 'i',
},
},
{
description: {
$regex: this.queryStr.keyword,
$options: 'i',
},
},
];
console.log(query);
this.mongooseQuery = this.mongooseQuery.find(query);
}
return this;
}
paginate() {
const page = this.queryStr.page * 1 || 1;
const limit = this.queryStr.limit * 1 || 50;
const skip = (page - 1) * limit;
this.mongooseQuery = this.mongooseQuery.skip(skip).limit(limit);
return this;
}
}
module.exports = ApiFeatures;
I think the problem is in the mongooseQuery.find because I call it twice the first with the Filter and the second with the Search I am not sure! , I tried but I didn’t find a solution.
