如何使用 pg-promise 将 jsonb[] 数据插入列

Sam*_*l G 2 pg-promise

给定一个包含 type 列的表jsonb[],如何将 json 数组插入到该列中?

使用提供的格式化程序在这种情况下:array不起作用:json- 除非我缺少正确的组合或其他东西。

const links = [
    {
        title: 'IMDB',
        url: 'https://www.imdb.com/title/tt0076759'
    },
    {
        title: 'Rotten Tomatoes',
        url: 'https://www.rottentomatoes.com/m/star_wars'
    }
];

 const result = await db.none(`INSERT INTO tests (links) VALUES ($1:json)`, [links]);
Run Code Online (Sandbox Code Playgroud)

vit*_*y-t 5

在这种情况下,您不需要库的:json过滤器,因为您需要一个 JSON 对象数组,而不是带有 JSON 对象数组的 JSON。

前者默认格式正确,后者只需要::json[]类型转换:

    await db.none(`INSERT INTO tests(links) VALUES($1::json[])`, [links]);
Run Code Online (Sandbox Code Playgroud)

其他注意事项

  • 使用pg-monitor或事件查询来输出正在执行的查询,以便于诊断。
  • 方法none只能解析为null,没有必要将结果存储在变量中。
  • pg-promise没有任何:array过滤器,请参阅支持的过滤器