我正在做一个Electron 商务API,我有这个类用于我的搜索查询,我使用正则表达式和带有 node 的类型脚本来实现这一点,我使用js node 项目来建立我的基础,但当我使用"Localhost:4000/api/Products/?Page=1"时,过滤器返回为空:
export class APIFeatures {
query: any;
queryStr: any;
constructor(query: any, queryStr: any) {
this.query = query,
this.queryStr = queryStr
}
search(): any {
const keyword = this.queryStr.keyword ? {
name: {
$regex: this.queryStr.keyword,
$options: 'i'
}
} : {}
this.query = this.query.find({ ...keyword })
}
filter(): any {
const queryCopy = { ...this.queryStr };
// Removing fields from the query
const removeFields = ['keyword', 'limit', 'page']
removeFields.forEach(el => delete queryCopy[el]);
// Advance filter for price, ratings etc
let queryStr = JSON.stringify(queryCopy)
queryStr = queryStr.replace(/\b(gt|gte|lt|lte)\b/g, match => `$${match}`)
// console.log(queryStr)
this.query = this.query.find(JSON.parse(queryStr));
return this;
}
pagination(resPerPage: any): any {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerPage * (currentPage - 1);
this.query = this.query.limit(resPerPage).skip(skip);
return this;
}
}
这就是产品控制器,我想在其中执行serach、过滤器和分页,以个性化来自产品数据库的查询:
async getAllProducts(req: Request, res: Response) {
try {
const resPerPage = 8;
const productCount = await prisma.product.count();
const apiFeatures = new APIFeatures(prisma.product.findMany(), req.query)
.search()
.filter()
.pagination(resPerPage)
const response = apiFeatures.query;
return res.status(200).send({ success: true, response,
productCount })
} catch (error) {
res.send({
message: error
})
}
}
问题是为什么我的查询返回为空