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

如何通过oracledb npm库遍历PL/SQL集合类型输出参数

如何遍历oracledb返回的自定义集合类型OUT参数

问题背景

我正在使用oracledb npm库调用带有OUT集合参数的PL/SQL函数,函数定义如下:

FUNCTION f_get_messages_for_processing (
  y_message_list        OUT thrgtw_adapter.tc_pcrf_message
) RETURN NUMBER

其中tc_pcrf_message的定义为:

create or replace type thrgtw_adapter.to_pcrf_message is object (
  id_message           number,
  message_type         number,
  msisdn               varchar2(15)
)

create or replace type thrgtw_adapter.tc_pcrf_message is table of thrgtw_adapter.to_pcrf_message

调用的JavaScript代码:

const statement = `
  BEGIN
    :ret := thrgtw_adapter.api_pcrf.f_get_messages_for_processing(:messageList);
  END;
`;

const variables = {
  ret: { dir: oracledb.BIND_OUT, type: oracledb.NUMBER},
  messageList: { dir: oracledb.BIND_OUT, type: 'THRGTW_ADAPTER.TC_PCRF_MESSAGE'}
};

return await db.execute(statement, variables);

问题现象

能在控制台看到返回的数据,但无法直接访问并遍历messageList:

const resultSet = await dbCommands.getMessagesForProcessing();

console.log(resultSet.outBinds.messageList)
console.log(typeof resultSet.outBinds.messageList) // 输出 'object'
console.log(Object.keys(resultSet.outBinds.messageList)) //输出 ['_impl']
resultSet.outBinds.messageList.forEach((item) => { // 报错 TypeError: resultSet.outBinds.messageList.forEach is not a function
  console.log(item)
})

控制台输出的数据:

[THRGTW_ADAPTER.TC_PCRF_MESSAGE] [
  { ID_MESSAGE: 1, MESSAGE_TYPE: 31, MSISDN: '421000000001' },
  { ID_MESSAGE: 2, MESSAGE_TYPE: 32, MSISDN: '421000000002' },
  { ID_MESSAGE: 3, MESSAGE_TYPE: 32, MSISDN: '421000000003' },
  { ID_MESSAGE: 4, MESSAGE_TYPE: 32, MSISDN: '421000000004' }
]

解决方案

你拿到的messageList是oracledb返回的OracleCollection对象,并非普通JavaScript数组,因此无法直接使用数组的forEach方法。可以通过以下两种方式遍历:

方法1:转换为普通数组

调用OracleCollection的getValues()方法将其转换为普通数组,之后就能使用所有数组方法:

const resultSet = await dbCommands.getMessagesForProcessing();
const messages = resultSet.outBinds.messageList.getValues();

messages.forEach(item => {
  console.log(item);
});

方法2:使用for...of循环

OracleCollection实现了可迭代接口,可以直接用for...of遍历:

const resultSet = await dbCommands.getMessagesForProcessing();

for (const item of resultSet.outBinds.messageList) {
  console.log(item);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:23:10