Search code examples
javascriptarrayssails.jssails-mongo

How to use Array attributes in sails.js model


Hi i am a new bee to sails and trying to get a model api that finally gives output as follows

[ 
  { 
    "icon" : [ 
      {"name":"ico1", "ico_typ":"fb", "ico_content_URL":"someLocation"},
      {"name":"ico2", "ico_typ":"tw", "ico_content_URL":"someLocation"},
      {...}
      ]
      "createdAt":
      "updatedAt":
     
  } 
]

I thought i can achieve this by passing the icon attribute as an Array but the problem is it passes the whole Array as string when i load it in REST CLIENT also i could not use the validation for values inside Array like without ico_type and URL the data should not be loaded into database. So, any suggestion about use of the 'array' where i'm wrong is very appreciated, thanks so much! Sails_v0.11.0 MongoDB_3.0.1


Solution

  • In your model define a method

    toJSON: function () {
       var obj = this.toObject();
       //say your obj.icon returns something like `'[{"name":"ico1","ico_typ":"fb","ico_content_URL":"someLocation"},{"name":"ico2","ico_typ":"tw","ico_content_URL":"someLocation"}]'`
       obj.icon = JSON.parse(obj.icon)
       return obj;
    },