Is it possible in Sailsjs to build more complex models

前端 未结 2 1498
陌清茗
陌清茗 2021-02-14 11:21

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

example:

{
   n         


        
相关标签:
2条回答
  • 2021-02-14 11:49

    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"
             }]
           }
    
    0 讨论(0)
  • 2021-02-14 11:52

    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.

    0 讨论(0)
提交回复
热议问题