Sequelize JSON data type

前端 未结 5 709
北荒
北荒 2021-02-02 14:22

I have defined a model as

module.exports = function (sequelize, DataTypes) {
  const MyModel = sequelize.define(\'MyModel\', {
    data: {
      type: DataTypes         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 14:43

    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.

提交回复
热议问题