Mongoose查询报错:Cannot read properties of undefined (reading 'propertyType')
Mongoose查询条件添加报错分析与解决
报错原因
初始定义的query对象中仅包含$or字段,不存在details属性。当执行query.details.propertyType = typePattern时,query.details为undefined,尝试读取其propertyType属性就会触发TypeError: Cannot read properties of undefined (reading 'propertyType')错误。
正确的查询条件添加方式
有两种常用的正确写法:
方式一:先初始化details对象
先确保query中存在details空对象,再给嵌套属性赋值:
// Only check for property if its not 'All' if (propertyType && propertyType !== 'All') { const typePattern = new RegExp(propertyType, 'i') // 确保details对象存在,不存在则创建空对象 query.details = query.details || {} query.details.propertyType = typePattern }
方式二:直接使用嵌套字段的字符串键赋值
利用MongoDB支持的点符号嵌套字段语法,直接通过字符串键添加查询条件,无需提前创建嵌套对象:
// Only check for property if its not 'All' if (propertyType && propertyType !== 'All') { const typePattern = new RegExp(propertyType, 'i') query['details.propertyType'] = typePattern }
这两种写法都能正确将propertyType的正则匹配条件添加到查询对象中,不会触发类型错误。
内容的提问来源于stack exchange,提问作者Zaritzki
相关产品推荐
相关产品推荐

