3

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

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
Anandapriyan S.D
  • 315
  • 4
  • 15

2 Answers2

1

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;
},
Muntasim
  • 6,689
  • 3
  • 46
  • 69
  • Yes That's Perfectly works but i also need to validate the contents inside the array like the array must be created only if it has the valid URL – Anandapriyan S.D Apr 03 '15 at 08:12
  • thats another issue, You can add something like `beforeCreate: function (values, next) { .... }` And you can accept the answer, so that other can be benefited :) – Muntasim Apr 03 '15 at 08:15
1

I think the model WaterLine gave you is already an JSON format, all you need to do is to use the right way to response it.

res.json(model);
Ryan Wu
  • 5,963
  • 2
  • 36
  • 47