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

问题描述 投票:1回答:1

给出一个具有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]);
pg-promise
1个回答
0
投票

在这种情况下,您不应使用库的:json过滤器,因为您需要一个JSON对象数组,而不是其中包含JSON对象数组的单个JSON。

默认情况下,前者的格式正确,此外,您只需要添加SQL类型转换:

    await db.none(`INSERT INTO tests(links) VALUES($1::json[])`, [links]);
  • 您应该使用pg-monitor或事件query来输出正在执行的查询,以便于诊断。
  • [方法none始终以null进行解析,没有结果存储在任何变量中。
© www.soinside.com 2019 - 2024. All rights reserved.