使用 knex 从 postgresql jsonb 中检索特定密钥

Retrieve particular key from postgresql jsonb using knex

我有 uploads_file table 和 formats 字段我只需要检索 formats.thumbnail

upload_file 架构

Column  Type    
id  integer Auto Increment [nextval('upload_file_id_seq')]  
name    character varying(255)  
formats jsonb NULL

在 strapi 内部,我通过以下方式使用 knex 来检索格式。

const knex = strapi.connections.default
const resp = await knex
          .select("upf.formats")
          .from("upload_file AS upf")  
return resp

结果是

[
  {
    "formats": {
      "large": {
        "ext": ".png",
        "url": "/uploads/large_sld1_acb6efc9cc.png",
        "hash": "large_sld1_acb6efc9cc",
        "mime": "image/png",
        "name": "large_sld1.png",
        "path": null,
        "size": 312.82,
        "width": 1000,
        "height": 564
      },
      "small": {
        "ext": ".png",
        "url": "/uploads/small_sld1_acb6efc9cc.png",
        "hash": "small_sld1_acb6efc9cc",
        "mime": "image/png",
        "name": "small_sld1.png",
        "path": null,
        "size": 96.62,
        "width": 500,
        "height": 282
      },
      "medium": {
        "ext": ".png",
        "url": "/uploads/medium_sld1_acb6efc9cc.png",
        "hash": "medium_sld1_acb6efc9cc",
        "mime": "image/png",
        "name": "medium_sld1.png",
        "path": null,
        "size": 192.46,
        "width": 750,
        "height": 423
      },
      "thumbnail": {
        "ext": ".png",
        "url": "/uploads/thumbnail_sld1_acb6efc9cc.png",
        "hash": "thumbnail_sld1_acb6efc9cc",
        "mime": "image/png",
        "name": "thumbnail_sld1.png",
        "path": null,
        "size": 29.8,
        "width": 245,
        "height": 138
      }
    }
  }
]

查询工作正常。但我只需要从中检索缩略图。因为它存储为 jsonb 格式不知道如何检索它。

提前致谢。

您可以使用->运算符

const knex = strapi.connections.default
const resp = await knex
          .select(
            knex.raw(`upf.formats->'thumbnail' as thumbnail`)
          )
          .from("upload_file AS upf")  
return resp