Node.js 如何使用knex和potsgres插入数组数据类型

Node.js 如何使用knex和potsgres插入数组数据类型,node.js,postgresql,knex.js,Node.js,Postgresql,Knex.js,我遇到了这个问题,时间不多了,请大家帮忙: 我想插入以下数据: const data= { id:user.id, choice:'SWOT', label:['Strengths','Weaknesses','Opportunities','Threats'], results:[45,5,20,30], description:'My first Strategic Analysis'} 在此表中: analyses ( id serial primary key, userID inte

我遇到了这个问题,时间不多了,请大家帮忙: 我想插入以下数据:

const data= {
id:user.id,
choice:'SWOT',
label:['Strengths','Weaknesses','Opportunities','Threats'],
results:[45,5,20,30],
description:'My first Strategic Analysis'}
在此表中:

analyses (
id serial primary key,
userID integer not null,
choice varchar(25) not null,
Label text ARRAY,
Results integer ARRAY,  
description varchar(200),
FOREIGN KEY (userID) REFERENCES users (id)
))

使用knex,这应该与smth类似:

db('analyses').insert({
        userid: data.id,
        choice: data.choice,
        Label:  data.labelG,
        Results: data.resultG,
        description: data.description
    }) 
由于这种语法对数组类型不起作用,我想知道怎么做? 有些人建议使用knex.raw(),但我无法获得正确的语法
有什么帮助吗

对于Postgresql的文本数组,您需要像以下那样存储数据:

{'Strengths','Weaknesses','Opportunities','Threats'}
为此,您可以创建一个函数来将其转换为通用

db('analyses').insert({
    userid: data.id,
    choice: data.choice,
    Label:  '{"' + data.labelG.join('","') + '"}',
    Results: data.resultG,
    description: data.description
})

当你获取它们时,你也需要转换它

您可以直接将javascript数组传递给
数组
类型的列。像这样:

await knex.schema.createTable('foo', t => {
  t.increments('id');
  t.specificType('intarray', 'integer ARRAY');
  t.specificType('stringarray', 'text ARRAY');
});

await knex('foo').insert({ intarray: [4,3,2,1], stringarray: ['foo','bar'] });

const rows = await knex('foo');
console.log(rows);

// should output: 
// [ anonymous { id: 1, intarray: [ 4,3,2,1 ], stringarray: [ 'foo', 'bar' ] } ]

您正在引用
数据.labelG
数据.resultG
,但您正在初始化
数据.label
数据。此答案中生成的结果
字符串似乎类似于
{“str1”,“str2”}
,而不是
{str1',str2'}
。然而,我想pg驱动程序也接受这种风格,因为这对提出问题的人是有效的。