29

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?

2
  • 1
    you'll have to serialize your array and store as a string. Commented Jan 26, 2017 at 8:13
  • 1
    Thanks @Adam, I was going to just store the data as a STRING, and then split the values later, but I thought there may be a less hacky way. Commented Jan 26, 2017 at 8:19

4 Answers 4

45

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

Sign up to request clarification or add additional context in comments.

Comments

15

You can define your field as json:

type: Sequelize.JSON

And then save the data as an array

2 Comments

I wanted to implement this idea, but the vsCode's intellisense adviced that it was only for postgreSQL. So I didn´t even tried
Yep, there are some kinds of data types that work only with some kinds of databases. You can read this doc to see if you can use or not a specific datatype.
4

This worked for me:

tags: {
    type: Sequelize.ARRAY(Sequelize.TEXT),
    defaultValue: [],
}

1 Comment

This worked with a MYSQL database?
0
favColors: {
    type: Sequelize.JSON
}

if you're using typescript you could set the type as

favColors: string[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.