Sequelize JSON data type

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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?

回答1:

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.



回答2:

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



转载请标明出处:Sequelize JSON data type
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!