You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Sequelize的findAll查询后无法获取返回字段值得到undefined是什么原因

问题原因

  • findAll 方法的配置参数传位错误:Sequelize的findAll仅接受一个配置对象作为入参,你把{raw: true}写在了第二个参数的位置,该配置完全没有生效。
  • findAll返回值为数组类型:从控制台打印结果可以看到schema的结构是[{"schema_name":"cbpo_davivienda_wiser"}],是被数组包裹的,直接访问数组本身的schema_name属性自然返回undefined。

修复方案

两种修改方式二选一即可:

方案1:保留findAll写法,修正参数位置+正确取值

async getSchemaName(id){
    if(id == 'public') return id
    let schema = await Cliente.findAll({
        attributes: ['schema_name'],
        where: {id: id},
        raw: true // 将raw配置移到第一个配置对象内
    })
    console.log(`aqui esta el esquema ${JSON.stringify(schema)}`)
    console.log(`aqui esta el esquema ${schema[0].schema_name}`) // 取数组第0项的属性
    return schema[0]?.schema_name ?? null // 可选链+空值合并做兼容,避免无数据时报错
}

方案2:改用findOne适配单条查询场景

按ID查询单条数据更适合用findOne,返回值直接是对象,不需要额外取数组下标:

async getSchemaName(id){
    if(id == 'public') return id
    let schema = await Cliente.findOne({
        attributes: ['schema_name'],
        where: {id: id},
        raw: true
    })
    console.log(`aqui esta el esquema ${JSON.stringify(schema)}`)
    console.log(`aqui esta el esquema ${schema.schema_name}`)
    return schema?.schema_name ?? null
}

内容的提问来源于stack exchange,提问作者Carlos Jaramillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:09:04