How to insert jsonb[] data into column using pg-promise

大憨熊 提交于 2019-12-11 05:43:06

问题


Given a table with a column of type jsonb[], how do I insert a json array into the column?

Using the provided formatters :array, :json won't work in this instance - unless I am missing the correct combination or something.

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]);

回答1:


You do not need the library's :json filter in this case, as you need an array of JSON objects, and not a JSON with an array of JSON objects.

The former is formatted correctly by default, which then only needs ::json[] type casting:

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

Other Notes

  • Use pg-monitor or event query to output queries being executed, for easier diagnostics.
  • Method none can only resolve with null, no point storing the result in a variable.
  • Library pg-promise does not have any :array filter, see supported filters.


来源:https://stackoverflow.com/questions/58758254/how-to-insert-jsonb-data-into-column-using-pg-promise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!