0

I have a simple REST application built in Sails and I want to save the correct data in a model attribute of type array.

Route to post

http://localhost:1337/locations/create?name=savassibeer&locations={latitude:23789472398.2344,longitude:2734637892.56756756}&locations={latitude:22.2344,longitude:2562.56756756,date:2014-02-15T11:00:00}

The result

{
  name: "savassibeer",
  locations: [
    "{latitude:23789472398.2344,longitude:2734637892.56756756}",
    "{latitude:22.2344,longitude:2562.56756756,date:2014-02-15T21:49:23.084Z}"
  ],
  createdAt: "2014-02-15T21:49:23.084Z",
  updatedAt: "2014-02-15T21:49:23.084Z",
  id: "52ffe0e345d19ec72b4fac77"
}

How can I transform the strings in locations to a valid JSON Object and save it?

marionebl
  • 3,342
  • 20
  • 34
Lucas Simon
  • 441
  • 1
  • 5
  • 10
  • Just to be sure to get your issue: Do you want to ensure the items in `locations.locations` are valid JSON strings before saving, save every item as actual js object or just get the js objects for the json strings? – marionebl Feb 16 '14 at 05:58
  • Plus: Which version of Sails / which Sails adapter do you use? – marionebl Feb 16 '14 at 06:14

1 Answers1

1

You're not going to be able to do this using URL shortcuts (i.e. hitting /locations/create in the browser). They're not designed to do type-guessing. If you want to save data this way, the answer is to write a custom create action in your Locations controller that will 1) validate the locations data as @marionebl mentions above, and 2) set the locations attribute as a Javascript array.

sgress454
  • 24,870
  • 4
  • 74
  • 92
  • Would you set the locations attribute as an array in the controller, or the model? – hamncheez Jan 12 '17 at 22:54
  • @hamncheez the `locations` attribute in this model is `type: 'array'` (which is really just an alias for `type: 'json'`). When you do `Locations.create()` in the controller action, that's when you'd set the `locations` value as an array (e.g. `Locations.create({locations: [{latitutde: 123, longitude: 456}, ... ]})`) – sgress454 Jan 17 '17 at 17:11