How to pass object as a data type to a data model in sequilize?

那年仲夏 提交于 2020-05-09 10:33:10

问题


I need to pass something that is not a primitive to the data type.

I am constructing something like this to send to the create method:

const p2 = {
          location_model: {
          latitude: lat,
           longitude: lng
      },
        establishment_id: createdEstablishment.id
      }

As you can see the establishment_id is of type Integer but the location_model is an object

This is my model

module.exports = {
  up: (queryInterface, DataTypes) => {
    return queryInterface.createTable('EstablishmentLocation', {
      location_model: {
        type: // need some datatype that accept's an object of that type
        allowNull: false,
        references: {
          model: 'Location',
          key: 'id',
        },
      },
      establishment_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'Establishment',
          key: 'id',
        },
      },
      createdAt: {
        allowNull: false,
        type: DataTypes.STRING,
        defaultValue: DataTypes.STRING,
      },
      updatedAt: {
        allowNull: false,
        type: DataTypes.STRING,
        defaultValue: DataTypes.STRING,
      }
    });
  },

  down: (queryInterface) => {
    return queryInterface.dropTable('EstablishmentLocation');
  }
};

My question is, how can I pass an object to a data type in sequilize?


回答1:


The type you provide in the model are the types defined in the database you use. If you are using postgresql, you can use DataTypes.JSON as the type.

If not, to save object, you can JSON.stringify the object and pass it as a string.



来源:https://stackoverflow.com/questions/61282783/how-to-pass-object-as-a-data-type-to-a-data-model-in-sequilize

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