Is it possible in Sailsjs to build more complex models

戏子无情 提交于 2019-12-04 18:30:34

问题


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

};

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/17106474/is-it-possible-in-sailsjs-to-build-more-complex-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!