最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sequelize Error on DataTypes.ARRAY(DataTypes.STRING) - Stack Overflow

programmeradmin0浏览0评论

I am new to NodeJs development I am using NodeJs with mysql and Sequelize to create a Batch model with these properties.

const Batch = sequelize.define(
  "Batch",
  {
    title: { type: DataTypes.STRING, allowNull: false },
    studentIds: { type: DataTypes.STRING },
    teacherId: { type: DataTypes.STRING, allowNull: true }
  },
  {
    timestamps: false
  }
);

On async method call it is working fine.

Batch.sync().then((res) => {
  console.log("Batch model sync : ", Batch === sequelize.models.Batch);
});

But I need to change

studentIds: { type: DataTypes.ARRAY(DataTypes.STRING)}

Whenever I make this change it gives error

I am using node 14.5.0 MySql 8.0.21 and Sequelize 6.3.4

I am new to NodeJs development I am using NodeJs with mysql and Sequelize to create a Batch model with these properties.

const Batch = sequelize.define(
  "Batch",
  {
    title: { type: DataTypes.STRING, allowNull: false },
    studentIds: { type: DataTypes.STRING },
    teacherId: { type: DataTypes.STRING, allowNull: true }
  },
  {
    timestamps: false
  }
);

On async method call it is working fine.

Batch.sync().then((res) => {
  console.log("Batch model sync : ", Batch === sequelize.models.Batch);
});

But I need to change

studentIds: { type: DataTypes.ARRAY(DataTypes.STRING)}

Whenever I make this change it gives error

I am using node 14.5.0 MySql 8.0.21 and Sequelize 6.3.4

Share Improve this question asked Aug 10, 2020 at 7:29 Atif ZiaAtif Zia 7932 gold badges12 silver badges31 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

DataTypes.ARRAY is not available on Mysql, it's only available on postgres.

Check in official docs: https://sequelize/api/v6/class/src/data-types.js~array

With a small workaround you can use your string data as an array. Overwrite the getter and setter of the property of the model

studentIds: {
    type: Sequelize.STRING,
    get() {
      const stringValue = this.getDataValue('studentIds');
      return stringValue ? rawValue.split(',') : null;
    },
    set(value) {
      const arrayValue = value ? value.join(',') : '';
      this.setDataValue('studentIds', arrayValue);
    },
  },
发布评论

评论列表(0)

  1. 暂无评论