为何无法访问Sequelize对象中[Op.or]形式的属性?如何解决?
Sequelize查询中无法访问where对象属性的问题解决
问题描述
构建Sequelize查询时,配置了如下where条件:
findOptions.where = { [Op.or]: [ { id: { [Op.iLike]: `%${search}%`, }, }, { serialNumber: { [Op.iLike]: `%${search}%`, }, }, ]};
调试时出现矛盾现象:
_.isEmpty(findOptions.where)返回truefindOptions.where[0]结果为unknownJSON.stringify(findOptions.where)返回{}Object.keys(findOptions.where)返回空数组
但console.log(findOptions.where)能输出预期结构:
{ [Symbol(or)]: [ { id: [Object] }, { serialNumber: [Object] } ] }
问题分析与解决
1. 问题原因
核心矛盾源于Symbol类型键的特殊性:
- Sequelize的
Op.or本质是一个Symbol值,而非普通字符串键 Object.keys()、JSON.stringify()、Lodash的_.isEmpty()这类工具默认只处理字符串类型的对象键,会直接忽略Symbol键- 而
console.log()打印对象时会展示所有键(包括Symbol),所以能显示出预期结构
2. 解决方案
针对Symbol键的特性,可通过以下方式正确访问和检测:
方法1:直接通过Op.or访问属性
既然Op.or是定义Symbol的变量,直接用它作为键访问即可:
// 获取or条件数组 const orConditions = findOptions.where[Op.or]; // 检测是否存在or条件 const hasOrCondition = !!findOptions.where[Op.or];
方法2:通过Symbol API遍历键
使用Object.getOwnPropertySymbols()获取对象的所有Symbol键,再进行操作:
const symbolKeys = Object.getOwnPropertySymbols(findOptions.where); // 检查是否包含Op.or对应的Symbol const hasOpOr = symbolKeys.includes(Op.or); // 获取对应的值 const orValue = findOptions.where[symbolKeys.find(key => key === Op.or)];
方法3:自定义空值检测逻辑(适配Lodash)
如果需要用_.isEmpty()风格的检测,可结合Symbol键的判断自定义逻辑:
const isWhereEmpty = (obj) => { const hasStringKeys = !_.isEmpty(obj); const hasSymbolKeys = Object.getOwnPropertySymbols(obj).length > 0; return !hasStringKeys && !hasSymbolKeys; }; // 使用自定义方法检测 console.log(isWhereEmpty(findOptions.where)); // 此时会正确返回false
内容的提问来源于stack exchange,提问作者aantia
相关产品推荐
相关产品推荐

