首页 > 解决方案 > 获取 postgres db 的 jsonb 列

问题描述

node-postgres用来选择和插入数据到postgres. 我有一些jsonb类型的列,我通过使用以下查询从 db 获取

getEmployee() {
 return SELECT empId, empData FROM employee WHERE empId = $1;
}

empData列的类型在哪里jsonb。下面是使用上述查询的代码片段。

const employee = await DBService.query(pgObj.getEmployee(), [empId]);

当我试图从中得到时empDataemployee我得到的是空值。

 const { empData } = employee;

我不确定我在这里缺少什么。这是获取dbjosnb列的正确方法吗?postgreasnodejs

标签: node.jsnode-postgres

解决方案


您确定empdata甚至在数据库中填充了吗?也许它是空的。另外,什么是 jsonb 字段empdata

要获取 的实际子字段empdata,您需要->>运算符。例如:

将整个 json 对象作为文本获取

SELECT empId, empData::text
FROM employee where empId = $1

获取单个属性

SELECT empId, empData->>annual_pay as salary
FROM employee WHERE empId = $1;

等等......你也可以试试看这里:https ://kb.objectrocket.com/postgresql/how-to-query-a-postgres-jsonb-column-1433

我还没有尝试过这些,我现在不在 postgres 面前。


推荐阅读