Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define array of objects in Sequelize.js?

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 ?

like image 656
Evan Lévesque Avatar asked Aug 29 '14 09:08

Evan Lévesque


Video Answer


2 Answers

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));
        }
    }
}
like image 99
mathisonian Avatar answered Oct 16 '22 08:10

mathisonian


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.

like image 42
scharfmedia Avatar answered Oct 16 '22 07:10

scharfmedia