How can I define an array of objects in Sequelize.js?

How to define array of objects 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 the corresponding datatype, am I missing something here?

+3


source to share


3 answers


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

  • We work with a relational database, and its principles also apply to Sequelize, which is an ORM for relational databases. The easiest way would be to create another table or object and link them as a 1: n relationship. In this case, add a new model to Sequelize and define its associations as described here: http://sequelizejs.com/articles/getting-started#associations You can have 2 tables. One profile table with N images.

  • If it's just a filename or a URL, you can serialize your Javascript array to a JSON string like:

    // before saving

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

    // after loading before using

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

  • If you are using PostgreSQL you can use array datatype for this field, see http://www.postgresql.org/docs/8.4/static/arrays.html

    or JSON Datatype:

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



Go to 1 if the object of the image is or will be more complex in this function. Or if you want to query by file name. Go to 2 if you won't be filtering data or complex data in the future.

Go to 3? I find it best to stick with the Sequelize abstraction and not use custom data types, even if possible in this case. Maybe you'd better stick with 1 or 2.

+7


source


I have successfully manipulated arrays by defining my model like this:



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));
        }
    }
}

      

+9


source


Try to define an array like

var profiles = { profile_id: 10, profile_pictures: { "pic1.jpg", "pic2.jpg", "pic3.jpg" }, profile_used_id: 12 }

-1


source







All Articles