Sequelize JSON data type

前端 未结 5 712
北荒
北荒 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:39

    Jalal's answer was great but didn't work for me unless I tweaked it a little. Here's what worked for me:

    First: create a migration that adds the field you want as type TEXT. example - I want to add a field called address to the Stores table:

    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.addColumn("Stores", "address", Sequelize.TEXT);
      },
    
      down: (queryInterface, Sequelize) => {
        return queryInterface.removeColumn("Stores", "address");
      }
    };
    

    Next: Inside your model, add the field with getters and setters to your list (object) of fields and datatypes:

    address: {
      type: DataTypes.TEXT,
        get: function() {
          return JSON.parse(this.getDataValue("address"));
        },
        set: function(value) {
          return this.setDataValue("address", JSON.stringify(value));
        }
    },
    

    So my entire model looks like this:

    module.exports = (sequelize, DataTypes) => {
      const Store = sequelize.define(
        "Store",
        {
          name: DataTypes.STRING,
          isActive: DataTypes.BOOLEAN,
          address: {
            type: DataTypes.TEXT,
            get: function() {
              return JSON.parse(this.getDataValue("address"));
            },
            set: function(value) {
              return this.setDataValue("address", JSON.stringify(value));
            }
          }
        },
        {}
      );
      Store.associate = function(models) {
        // associations can be defined here
        Store.hasMany(models.Order, {
          foreignKey: "id",
          targetKey: "storeId"
        });
      };
      return Store;
    };
    

    Now you can create and retrieve records just like you would with a JSON type field in the db.

    For example: const store = await Store.create({name: "Joe's corner store", address: {address1: "123 test street", city: "Los Angeles", state: "CA"}})

    Some notes:

    In the above code blocks...

    • Replace address with the field name you want to use.
    • Replace Stores with your model/table name.
    • I added return on the setter, otherwise it was erroring out when trying to create a new record (the way Jalal has it).

提交回复
热议问题