Omid Hashemi
Omid Hashemi

Reputation: 207

Is it possible in Sailsjs to build more complex models

I would like to have arrays or collections in my model, is this yet possible with waterline (mongoDB)? are there any alternatives around?

example:

{
   name: Bundle,
   col1 : {
      name : anOtherModel,
      subCol: {
         text: aString,
         ...
      }
   },
   col2 : {
      name : anOtherModel,
      subCol: {
         text: aString,
         ...
      }
   }
}

to:

module.exports = {

    attributes : {

        name : {
            type : 'STRING',
            required : true
        },
        basicModules: {
            type : 'ARRAY', // or 'COLLECTION'
            required : false
        }
    }

};

Upvotes: 10

Views: 2851

Answers (2)

bobbor
bobbor

Reputation: 141

I don't know if this is still an issue, but the trick is to neither POST as "form-data" nor "x-www-url-encoded". You have to POST the "raw" content:

Assume the situation:
http://www.example.com/mymodel


form-data

Your Header may look like this:

POST /mymodel/create HTTP/1.1
Host: www.example.com
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="basicModules"

[1,2,3,4]
----WebKitFormBoundaryE19zNvXGzXaLvS5C

the result is that a string "[1,2,3,4]" gets (type-)validated, which fails


x-www-url-encoded

In this case the Header is something like this:

POST /mymodel/create HTTP/1.1
Host: www.example.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

basicModules=%5B1%2C2%2C3%2C4%5D

which has exactly the same result as form-data. validation fails because of basicModules being the string "[1,2,3,4]"


raw

to make it work your Header has to look like this:

POST /mymodel/create HTTP/1.1
Host: www.example.com
Cache-Control: no-cache

{"basicModules":[1,2,3,4]}

which results in just exactly what you want, and type validation works.


so in the end, you can fill the most complex models that way in JSON. e.g.

POST /mymodel/create HTTP/1.1
Host: www.example.com
Cache-Control: no-cache

{"user": {
         "name": {
           "first":"John",
           "last":"Doe"
         },
         "age":25,
         "pets":[{
           "name":"Garfield",
           "type":"cat"
         },
         {
           "name":"Rudolph",
           "type":"reindeer"
         }]
       }

Upvotes: 3

Jérémie Parker
Jérémie Parker

Reputation: 3174

If you're looking for model associations, it's not there yet (look at this issue for proposed implementations) if you'd just like to have arrays of data stored in DB, you can have arrays as attribute (see the doc for reference on that). I haven't tested it but I guess it will serialize the array prior to saving it in the DB if it doesn't have a matching structure.

Upvotes: 2

Related Questions