Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize JSON data type

Tags:

I have defined a model as

module.exports = function (sequelize, DataTypes) {   const MyModel = sequelize.define('MyModel', {     data: {       type: DataTypes.JSON,       ...     },     ...   });    return MyModel; }; 

I query it using

MyModel.findAll().then(myModels => ...); 

However, data field in the query result is a string, not a JSON object. How do I fix it?

like image 850
MikkoP Avatar asked Dec 22 '16 10:12

MikkoP


People also ask

How do I store JSON in Sequelize?

Create a database and a Schema: var Sequelize = require('sequelize'), JsonField = require('sequelize-json'), db, User; db = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', logging: false }); User = db. define('User', { username: Sequelize. STRING, jsonField: JsonField(db, 'User', 'jsonField') });

How do you define varchar in Sequelize?

If you give the datatype as TEXT in Sequelize It will automatically convert that field to NVARCHAR(MAX ) for SQL Server database. But it is mentioned in Sequelize github repository from line 79 to 90. Show activity on this post. postgres supports Upto 1G for BOTH TEXT AND VARCHAR.


1 Answers

It's not supported yet MySQL JSON Data Type #4727. But you can do something like this:

 module.exports = function (sequelize, DataTypes) {       const MyModel = sequelize.define('MyModel', {         data: {           type: Sequelize.TEXT,            get: function () {                 return JSON.parse(this.getDataValue('value'));             },             set: function (value) {                 this.setDataValue('value', JSON.stringify(value));             },     ,           ...         },         ...       });        return MyModel; }; 

I also found this package on github sequelize-json you can give it a try if you don't want to use getters and setters.

like image 98
Jalal Avatar answered Sep 17 '22 12:09

Jalal