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

Node.js向PostgreSQL插入对象数组时非id字段为null问题排查

问题原因

核心问题是PostgreSQL标识符的大小写处理规则与JSON键名不匹配:

  • PostgreSQL中,未用双引号包裹的标识符会自动转为小写。你在json_to_recordset的定义里写的avgHighPrice INT,实际会被识别为avghighprice。
  • 但你的JSON数据中的键是驼峰式的"avgHighPrice",与PostgreSQL识别的小写字段名不匹配,导致无法提取对应值,返回null。
  • id字段能正常插入是因为JSON键"id"和PostgreSQL识别的小写id名称一致。

解决方案

在json_to_recordset的字段定义中,用双引号包裹驼峰式字段名,强制PostgreSQL保留大小写:

修正后的Node.js代码

await db.query(`
  INSERT INTO ticker_summary (id, open_high, open_low) 
  SELECT x.id, x."avgHighPrice", x."avgLowPrice" 
  FROM json_to_recordset($1) AS x (
    "avgHighPrice" INT, 
    "highPriceVolume" INT, 
    "avgLowPrice" INT, 
    "lowPriceVolume" INT, 
    id INT
  );
`, [JSON.stringify(array)]);

修正后的PostgreSQL测试代码

INSERT INTO ticker_summary (id, open_high, open_low) 
SELECT x.id, x."avgHighPrice", x."avgLowPrice"
FROM json_to_recordset('[{"avgHighPrice":153,"highPriceVolume":61308,"avgLowPrice":151,"lowPriceVolume":11252,"id":"2"},{"avgHighPrice":194920,"highPriceVolume":1,"avgLowPrice":182001,"lowPriceVolume":1,"id":"6"},{"avgHighPrice":187121,"highPriceVolume":4,"avgLowPrice":178642,"lowPriceVolume":2,"id":"10"}]') 
AS x ("avgHighPrice" INT, "highPriceVolume" INT, "avgLowPrice" INT, "lowPriceVolume" INT, id INT);

额外验证步骤

你可以先单独执行SELECT语句确认解析是否正常:

SELECT x.id, x."avgHighPrice", x."avgLowPrice"
FROM json_to_recordset('[{"avgHighPrice":153,"id":"2"}]') 
AS x ("avgHighPrice" INT, id INT);

如果返回的avgHighPrice值正确,说明字段匹配问题已解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:44:56