首页 > 解决方案 > 如何将对象作为数据类型传递给 sequilize 中的数据模型?

问题描述

我需要将一些不是原始数据类型的东西传递给数据类型。

我正在构建这样的东西来发送到 create 方法:

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

如您所见,integer_id 是 Integer 类型,但 location_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');
  }
};

我的问题是,如何将对象传递给 sequilize 中的数据类型?

标签: javascriptnode.jssequelize.js

解决方案


您在模型中提供的type是您使用的数据库中定义的类型。如果您使用postgresql,则可以DataTypes.JSON用作类型。

如果没有,要保存对象,您可以JSON.stringify将对象作为字符串传递。


推荐阅读