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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

You can define your field as json:

type: Sequelize.JSON

And then save the data as an array


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x