首页 > 解决方案 > 如何从 Postgres 的 QueryResult 数组中提取行

问题描述

我将我的数据库响应作为一个数组获取,这是运行两个查询的结果。我需要提取结果中存在的行。如何提取具有对象的行?

或者任何其他正确获取数据的方法?请注意,我同时运行了两个查询,这就是为什么得到这样的响应。

我没有在这里粘贴任何尝试过的代码,所以请原谅我。

[ Result {
command: 'SELECT',
rowCount: 7,
oid: null,
rows:
 [ [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object] ],
fields: [ [Field], [Field], [Field] ],
_parsers:
 [ [Function: parseBigInteger],
   [Function: noParse],
   [Function: noParse] ],
_types: TypeOverrides { _types: [Object], text: {}, binary: {} },
RowCtor: null,
rowAsArray: false },
Result {
command: 'SELECT',
rowCount: 11,
oid: null,
rows:
 [ [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object] ],
fields: [ [Field], [Field], [Field] ],
_parsers:
 [ [Function: parseBigInteger],
   [Function: noParse],
   [Function: noParse] ],
_types: undefined,
RowCtor: null,
rowAsArray: false } ]

JSON.stringify(dbres, null, 4) 给了我

[
{
    "command": "SELECT",
    "rowCount": 7,
    "oid": null,
    "rows": [
        {
            "count": "11",
            "a_id": "solution",
            "a_description": "Solution"
      }]
}]

标签: node.jstypescriptpostgresql

解决方案


您需要首先查看查询的结果,然后为每个查询映射行。以下应该或多或少的伎俩

interface IQResult {
    queryId: number;
    queryResults: Array<Record<string, any>>;
}

    const t =
        dbres &&
        dbres.map((res, index) => {
            let qResult: IQResult = {
                queryId: index,
                queryResults: [],
            };

            res &&
                res.forEach(
                    (r) =>
                        (qResult = {
                            ...qResult,
                            queryResults: [...qResult.queryResults, ...r.rows],
                        })
                );
        });

推荐阅读