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?

2
  • 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? Commented Feb 16, 2014 at 5:58
  • Plus: Which version of Sails / which Sails adapter do you use? Commented Feb 16, 2014 at 6:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you set the locations attribute as an array in the controller, or the model?
@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}, ... ]}))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.