映射数据库数据到对象后出现Null值问题排查
问题解决:处理Null值导致的TypeError
问题根源
过滤逻辑中直接对choice.item_desc调用toLowerCase(),但该字段存在null值——null属于原始值,没有toLowerCase()方法,因此触发Cannot read properties of null (reading 'toLowerCase')错误。
解决方案
1. 过滤时先校验字段非空
在过滤条件里先判断choice.item_desc是否不为null,再执行字符串匹配逻辑,避免对null调用方法。
2. 优化冗余的JSON转换
Sequelize的findAll()返回的是模型实例数组,不需要通过JSON.stringify()+JSON.parse()转换,直接读取实例属性就能拿到纯数据对象,提升代码效率。
修改后的完整代码
async autocomplete(interaction) { const focusedValue = interaction.options.getFocused().toLowerCase(); const choices = await items.findAll({ attributes: ['itemID', 'desc_de'] }); // 直接转换Sequelize实例为纯对象,无需JSON序列化再解析 const itemObj = choices.map(item => ({ itemID: item.itemID, item_desc: item.desc_de, })); // 先判断item_desc非空,再执行匹配 const filtered = itemObj.filter(choice => choice.item_desc !== null && choice.item_desc.toLowerCase().includes(focusedValue) ); await interaction.respond( filtered.map(choice => ({name: choice.item_desc, value: choice.itemID})), ); }
额外优化点
- 提前将
focusedValue转为小写,避免在过滤循环里重复调用toLowerCase(),提升性能 - 如果希望null值的记录也能被匹配(比如用户输入空值时),可以调整过滤逻辑为:
choice.item_desc === null || choice.item_desc.toLowerCase().includes(focusedValue)
内容的提问来源于stack exchange,提问作者Christoph Ritzer
相关产品推荐
相关产品推荐

