Search code examples
javascriptnode.jspostgresqlpostmanknex.js

Storing objects in JSONB column using Postgres/Knex


I created a graphs table on my back end to store graph related data. Here is the schema from the Knex migration file:

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');
        })
  )
};

Here is an example of the type of data that I am trying to store in the jsonb column in my database:

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

Now here is the request that I tried to send through 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"
}

I received the following error: SyntaxError: Unexpected token in JSON at position 44. I came across this article when I was trying to figure out what is going on:

sending nested json object using postman

I have my Content-Type header set to application/json, and Postman isn't giving me a signal that I'm sending a bad request. I'm not sure what the problem is.

It's also possible that I'm thinking about this the wrong way. When I was looking at the Postgres docs, it seemed to me that the best way to store the type of object that I'm trying to store would be with a jsonb column. But if that is not the case, I'm open to suggestions. Any help would be greatly appreciated.


Solution

  • From the look of graph_info in the result, it is not a valid JSON, but a string that contains js object.

    When you saves your data to the JSONB column, you need to apply the JSON.stringify method on the object.

    For example like this:

    {
        "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"
    }