繁体   English   中英

使用 Postgres/Knex 在 JSONB 列中存储对象

[英]Storing objects in JSONB column using Postgres/Knex

我在后端创建了一个图表来存储图表相关数据。 这是 Knex 迁移文件中的架构:

exports.up = function(knex) {
  return (
      knex.schema
        .createTable('users', tbl => {
            tbl.increments();
            tbl.string('username', 255).notNullable();
            tbl.string('password', 255).notNullable();
            tbl.string('name', 255).notNullable();
            tbl.string('email', 255).unique().notNullable();
        })
        .createTable('graphs', tbl => {
          tbl.increments();
          tbl.string('graph_name', 255).notNullable();
          tbl.jsonb('graph_info').notNullable();
          tbl
            .integer('user_id')
            .unsigned()
            .notNullable()
            .references('id')
            .inTable('users')
            .onDelete('CASCADE')
            .onUpdate('CASCADE');
        })
  )
};

以下是我尝试存储在数据库的 jsonb 列中的数据类型示例:

{
  labels: ['Axis1', 'Axis2', 'Axis3'],
  datasets: [
        {
          label: 'Dataset1',
          borderDash: [0, 0],
          backgroundColor: '#fff',
          data: [25, 14, 22],
        },
      ],
  title: 'Graph1',
}

现在这是我尝试通过 Postman 发送的请求:

{
    "graph_name": "test10",
    "graph_info": "{
        labels: ['Axis1', 'Axis2', 'Axis3'],
        datasets: [
            {
              label: 'Dataset1',
              borderDash: [0, 0],
              backgroundColor: '#fff',
              data: [25, 14, 22],
            },
                ],
            title: 'Graph1'
        }",
    "user_id": "1"
}

我收到以下错误: SyntaxError: Unexpected token in JSON at position 44 当我试图弄清楚发生了什么时,我偶然发现了这篇文章:

使用邮递员发送嵌套的 json 对象

我的 Content-Type 标头设置为application/json ,邮递员没有给我一个信号,表明我正在发送一个错误的请求。 我不确定问题是什么。

我也有可能以错误的方式思考这个问题。 当我查看 Postgres 文档时,在我看来,存储我要存储的对象类型的最佳方法是使用 jsonb 列。 但如果情况并非如此,我愿意接受建议。 任何帮助将不胜感激。

从结果中的graph_info来看,它不是一个有效的JSON,而是一个包含js对象的字符串。

将数据保存到 JSONB 列时,需要对对象应用JSON.stringify方法。

例如像这样:

{
    "graph_name": "test10",
    "graph_info": JSON.stringify({
        labels: ['Axis1', 'Axis2', 'Axis3'],
        datasets: [
            {
              label: 'Dataset1',
              borderDash: [0, 0],
              backgroundColor: '#fff',
              data: [25, 14, 22],
            },
        ],
        title: 'Graph1'
    }),
    "user_id": "1"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM