Home > Mobile >  How to define an array in my models using mysql sequelize | node.js
How to define an array in my models using mysql sequelize | node.js

Time:08-09

This is the result what I need to store in DB :

sellers : [{'test1'},{'test2'},{'test3'}]

And this is my model:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      id: {
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        type: DataTypes.INTEGER,
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      sellers: [
       {
        type: DataTypes.STRING,
        allowNull: true,
      },
    ],
    },
    {
      timestamps: true,
      defaultScope: {
        attributes: {
          exclude: ["password"],
        },
      },
      scopes: {
        withPassword: {
          attributes: {},
        },
      },
      indexes: [
        {
          unique: true,
          fields: ["email"],
        },
      ],
    }
  );

  return User;
};

And the error is :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

CodePudding user response:

 sellers: [
   {
    type: DataTypes.ARRAY(DataTypes.STRING),
    allowNull: true,
  }

CodePudding user response:

You need to slightly change your schema definition as,

sellers: {
  type: DataTypes.ARRAY(DataTypes.JSON),
  allowNull: true,
  defaultValue: [],
  get() {
    const data = this.getDataValue('sellers');
    const queryResponse = [];
    data.forEach(seller => {
      queryResponse.push(JSON.parse(seller));
    });
    return queryResponse;
  },
  set(seller) {
    return this.setDataValue('sellers', JSON.stringify(seller));
  }
},
  • Related