【问题标题】:,column <columnName> is of type jsonb but expression is of type text[],column <columnName> 是 jsonb 类型,但表达式是 text[] 类型
【发布时间】:2017-03-28 02:51:41
【问题描述】:

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

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

我只是将 req.body 对象(来自 Express)传递给数据库。

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

**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

我认为它的驱动程序问题 cos 数组:formatting.js [in pg-promise lib] 中的函数 (arr) 返回字符串,而 postgres 无法消化它。如果数组嵌套在任何对象中,那么它可以顺利工作,例如

"MyPref" : {Same Object array as above}

MyPref 在“FoodPref”列中通过,没有任何问题。

【问题讨论】:

  • 您应该附上您正在执行的确切查询。要在不执行的情况下获取查询,请使用方法pgp.as.format
  • 我要求您使用pgp.as.format 来更新正在生成的查询的问题,而不是您传递给查询方法的内容。
  • 抱歉 :( 无法获取查询...请提供示例代码和位置以生成查询。我尝试 response.log in .one 方法,但返回的查询与我放入的相同查询问题
  • 调用pgp.as.format(query, values),返回格式化后的查询字符串。

标签: arrays postgresql jsonb pg-promise


【解决方案1】:

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

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

如果你把它作为一个对象属性传入,它就像你说的那样工作。要将其作为参数传递到数组内,您需要将其传递到数组内

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

query('bla-bla $1', [data])

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

query('bla-bla $1', data)

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

更新

See also this related question.

【讨论】:

  • 那么我应该停止直接传递 req.body 并为每列创建单独的对象吗? (检查用于插入的查询的更新问题)
  • 抱歉回复晚了...通过传递单个对象作为参数代替 req.body 解决了这个问题....另外在 json.stringify 中传递了具有 JSON 数组的变量。
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 2016-05-15
  • 2022-08-22
  • 2018-05-04
  • 1970-01-01
  • 2018-10-09
  • 2016-10-19
  • 2023-02-09
相关资源
最近更新 更多