Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a datatype of array in mysql Sequelize instance?

I am building an application that uses Node/Express and MySQL with Sequelize as the ORM. I want to have a datatype of Array, but the sequelize docs says this is limited to postgres only.

Basically, if I have a users table that has 3 columns for example (name, phone, favColors), I want favColors to get populated with an array of string values retrieved from the user. How can I do this?

like image 586
johnny_mac Avatar asked Jan 25 '17 20:01

johnny_mac


People also ask

Can you store an array in MySQL?

Although an array is one of the most common data types in the world of programming, MySQL actually doesn't support saving an array type directly. You can't create a table column of array type in MySQL. The easiest way store array type data in MySQL is to use the JSON data type.

How do you define varchar in Sequelize?

If you give the datatype as TEXT in Sequelize It will automatically convert that field to NVARCHAR(MAX ) for SQL Server database. But it is mentioned in Sequelize github repository from line 79 to 90. Show activity on this post. postgres supports Upto 1G for BOTH TEXT AND VARCHAR.

Can we use Sequelize in MySQL?

Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.

How do I add data using Sequelize?

To insert new rows into your SQL table, you need to first create a Sequelize Model object. In Sequelize, a Model is an object that represents your SQL table, giving information to Sequelize about the name, the columns, and their data types.


1 Answers

You can use getter/setter functions for this:

favColors: {
    type: Sequelize.STRING,
    allowNull: false,
    get() {
        return this.getDataValue('favColors').split(';')
    },
    set(val) {
       this.setDataValue('favColors',val.join(';'));
    },
}

more info: https://sequelize.org/master/manual/getters-setters-virtuals.html

like image 155
Adam Avatar answered Sep 18 '22 06:09

Adam