,column <columnName>的类型为jsonb,但表达式的类型为text []

sun*_*pta 8 arrays postgresql jsonb pg-promise

有如下数组,需要保存在JSONB列中:

[{"FoodType":"veg","pref":"High"}
,{"FoodType":"sea food","pref":"Medium"}
,{"FoodType":"Chicken","pref":"Low"}]
Run Code Online (Sandbox Code Playgroud)

我只是传递req.body对象(来自Express)以插入到DB.

db.one('insert into foodies(FoodieName, FoodPref,country,languagePref)' +
'values(${FoodieName}, $[FoodPref], ${country} ,${languagePref})  RETURNING FoodieId',req.body)
Run Code Online (Sandbox Code Playgroud)

**PG DB通过pg-promise库引发错误:

{ [error: column "foodpref" is of type jsonb but expression is of type text[]]
name: 'error',
length: 196,
severity: 'ERROR',
code: '42804',
detail: undefined,
hint: 'You will need to rewrite or cast the expression.',
position: '123',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_target.c',
line: '529',
routine: 'transformAssignedExpr' }
POST /api/member 500 638.510 ms - 57
Run Code Online (Sandbox Code Playgroud)

我认为它的驱动程序问题cos数组:format.js中的函数(arr)[在pg-promise lib中]返回字符串并且postgres不能消化它.如果数组嵌套在任何对象中,那么它可以顺利运行,例如

"MyPref" : {Same Object array as above}
Run Code Online (Sandbox Code Playgroud)

这里MyPref在"FoodPref"列中没有任何问题.

vit*_*y-t 3

如果数组嵌套在任何对象中,那么它可以顺利工作

它表明您没有正确传递格式化数据。您不是将 JSONB 数据作为数组传递,而是传递内部对象数组。

如果您将其作为对象属性传递,它就会按照您所说的那样工作。要将其作为数组内的参数传递,您需要将其传递到数组内

var data = [{"FoodType":"veg","pref":"High"}
,{"FoodType":"sea food","pref":"Medium"}
,{"FoodType":"Chicken","pref":"Low"}]

query('bla-bla $1', [data])
Run Code Online (Sandbox Code Playgroud)

即你的问题是你将其传递为:

query('bla-bla $1', data)
Run Code Online (Sandbox Code Playgroud)

它将数组 - JSONB 数据误解为值数组 - 参数。

更新

另请参阅此相关问题