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?
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.
JSON data types aren't supported for MySQL.
See the docs here http://docs.sequelizejs.com/en/v3/docs/models-definition/#data-types
A work around could be to use text and stringify/parse when querying it