获取全部产品时触发TypeError:无法读取undefined的query属性
解决获取全部产品接口的TypeError问题
问题概述
- 报错信息:
TypeError: Cannot read properties of undefined (reading 'query') - 异常现象:单个产品查询功能正常,但获取全部产品的接口请求失败;数据库内存在2个测试产品,此前功能正常,未修改相关文件但当前无法通过Postman获取数据
- 错误定位:
productController.js中const products = await apiFeatures.query;这一行
错误原因分析
问题出在APIFeatures类的pagination方法中:该方法没有返回当前类实例(this),而search和filter方法都正确实现了返回this的逻辑。当链式调用new APIFeatures(...).search().filter().pagination(...)时,执行到pagination步骤后会返回undefined,导致apiFeatures变量被赋值为undefined,后续访问apiFeatures.query自然触发“读取undefined属性”的错误。
修复方案
修改APIFeatures.js中的pagination方法,添加return this;语句,确保链式调用始终返回类实例:
修改后的APIFeatures.js完整代码
const { remove } = require("../models/product"); class APIFeatures { constructor(query, queryStr) { this.query = query; this.queryStr = queryStr; } search() { const keyword = this.queryStr.keyword ? { name: { $regex: this.queryStr.keyword, $options: 'i' // Case insensitive option } } : {} this.query = this.query.find({ ...keyword }) return this; } filter() { const queryCopy = { ...this.queryStr }; // Remove the fields from the query string const removeFields = ['keyword', 'limit', 'page'] removeFields.forEach(el => delete queryCopy[el]); // Advanced filtering let queryStr = JSON.stringify(queryCopy); queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in)\b/g, match => `$${match}`); this.query = this.query.find(JSON.parse(queryStr)); return this; } pagination(resPerPage) { const currentPage = Number(this.queryStr.page) || 1; const skip = resPerPage * (currentPage - 1); this.query = this.query.limit(resPerPage).skip(skip); return this; // 新增返回当前实例的语句 } } module.exports = APIFeatures;
验证说明
修改后,链式调用search().filter().pagination()会持续返回APIFeatures实例,apiFeatures变量能正确持有实例对象,访问apiFeatures.query即可正常执行MongoDB查询,获取全部产品数据。
内容的提问来源于stack exchange,提问作者ademclk
相关产品推荐
相关产品推荐

