如何在pg-promise中使用JSONB操作

时间:2018-08-11 03:22:11

标签: node.js postgresql jsonb pg-promise node-postgres

我正在努力与pg-promise并使其与JSONB一起使用。我正在使用准备好的语句,为此SQL命令尝试了两种变体(我只是想用一组新值(基本上是附加值)对jsonb列进行udping):

  db.none({
    name: 'updateLike',
    text:`UPDATE posts
    SET likes_by = jsonb_set(likes_by, '{$1~}', '$2~'),
    likes_count = likes_count + 1
    WHERE post_id = $3`,
    values: [user_id, username, pid]
  })

  db.none({
    name: 'updateLike',
    text:`UPDATE posts
          SET likes_by = likes_by || '{"$1": "$2"}',
          likes_count = likes_count + 1
          WHERE post_id = $3`,
    values: [user_id, username, pid]
  })

它给我以下错误:

错误:json类型的输入语法无效

错误:无法确定参数$ 1的数据类型

有人做过吗?

1 个答案:

答案 0 :(得分:1)

这就是我最终要做的:

  db.none(`UPDATE posts
           SET likes_by = likes_by || '{$1~: $2~}',
           likes_count = likes_count + 1
           WHERE post_id = $3#`,
           [user_id, username, pid]
  )

工作。谢谢!