Home > Back-end >  sequelize : converting json column to object on findAll
sequelize : converting json column to object on findAll

Time:12-29

i have a page table with a data column which technically is a longtext since im using mysql but i have defined it as JSON in my model and i store json data in that coumn

here is my model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Page extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Page.init(
    {
      user_id: DataTypes.INTEGER,
      type: DataTypes.STRING,
      data: DataTypes.JSON,
    },
    {
      sequelize,
      modelName: "Page",
      underscored: true,
    }
  );
  return Page;
};

when i create a row in my table and return the result i can see data column as object , and in database i have it as a json string (done automatically by sequelize i think since im not converting it to json before storing )

{
    "result": {
        "id": 5,
        "type": "text",
        "user_id": 1,
        "data": {
            "title": "hi",
            "text": "something"
        },
        "updatedAt": "2022-12-28T18:29:27.781Z",
        "createdAt": "2022-12-28T18:29:27.781Z"
    }
}

enter image description here but then when i read all the pages from database with findAll the result data is a json string

{
    "pages": [
        {
            "id": 5,
            "user_id": 1,
            "type": "text",
            "data": "{\"title\":\"hi\",\"text\":\"something\"}",
            "createdAt": "2022-12-28T18:29:27.000Z",
            "updatedAt": "2022-12-28T18:29:27.000Z"
        }
    ]
}

is there anyway to convert json string to obejct in findAll ?

CodePudding user response:

This is a common issue when using sequelize with Mysql - Please Check https://stackoverflow.com/a/43002437/9782005

  • Related