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?
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') });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With