简体   繁体   中英

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 ?

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

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.

尝试像这样定义一个数组

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM