14

How can I define an array of objects field in Sequelize.js model?
I need something like this

{
    "profiles" : [
        {
            "profile_id": 10,
            "profile_pictures" : ["pic1.jpg","pic2.jpg","pic3.jpg"],
            "profile_used_id" : 12
        },
        ... // more profiles
    ]
}

I checked the docs, but couldn't find a relevant data type, am I missing something here ?

2 Answers 2

30

I have successfully been mimicking arrays by defining my model like:

var MyModel = sequelize.define('MyModel', {
    myArrayField: { 
        type: DataTypes.STRING, 
        get: function() {
            return JSON.parse(this.getDataValue('myArrayField'));
        }, 
        set: function(val) {
            return this.setDataValue('myArrayField', JSON.stringify(val));
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

with defaultValue: '[]'
with type: DataTypes.STRING
13

I can think currently of 2 solutions (and a 3rd one if you are using PostgreSQL).

  1. We have a relational database working behind, so do its principles apply also for Sequelize which is a ORM for relational databases. The easiest would be to create another table or entity and associate them as a 1:n relationship. For that matter add a new model in Sequelize and define its associations like described here: http://sequelizejs.com/articles/getting-started#associations You might have then 2 tables. One profile table having N pictures.

  2. If its just a filename or url you could serialise a Javascript array to a JSON string like:

    // before save

    var mypics = ["pic1.jpg","pic2.jpg"]; profile.pictures = JSON.stringify( mypics ); profile.save()

    // after load before use

    var profile = Profile.get(1) pictures = JSON.parse(profile.pictures);

  3. If you use PostgreSQL you could use the Array Datatype for this field, see: http://www.postgresql.org/docs/8.4/static/arrays.html

    or the JSON Datatype:

    http://www.postgresql.org/docs/9.3/interactive/datatype-json.html

Go for 1 if your Picture object is or will be more complex in the feature. Or if you want to query by filename. Go for 2 if you dont do any data filtering or complex data in the future.

Go for 3? I think its best to stick to Sequelize abstraction and not use custom data types even its possible in that case. Maybe you better stick to 1 or 2.

2 Comments

So Let's say I use Postgres, I would define the array of Objects like Sequelize.ARRAY(Sequelize.JSON) right?
Sequelize.ARRAY(Sequelize.JSON) does not work

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.