Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
    }

};
like image 828
Omid Hashemi Avatar asked Jun 14 '13 10:06

Omid Hashemi


2 Answers

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"
         }]
       }
like image 161
bobbor Avatar answered Nov 15 '22 21:11

bobbor


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.

like image 2
Jérémie Parker Avatar answered Nov 15 '22 21:11

Jérémie Parker