Javascript 如何使用Sails.js扩展REST API中的嵌套关系

Javascript 如何使用Sails.js扩展REST API中的嵌套关系,javascript,node.js,rest,sails.js,Javascript,Node.js,Rest,Sails.js,我是NodeJS和Sails.js的新手 我想创建一个RESTAPI,它允许我根据查询参数扩展资源。例如 HTTP GET /snippets { "count": 1, "next": null, "previous": null, "results": [ { "url": "http://localhost:8000/snippets/1/", "highlight": "htep://localhost:8000/snippets/1/

我是NodeJS和Sails.js的新手

我想创建一个RESTAPI,它允许我根据查询参数扩展资源。例如

HTTP GET /snippets


{
"count": 1, 
"next": null, 
"previous": null, 
"results": [
    {
        "url": "http://localhost:8000/snippets/1/", 
        "highlight": "htep://localhost:8000/snippets/1/highlight/", 
        "title": "test", 
        "code": "def test():\r\n     pass", 
        "linenos": false, 
        "language": "Clipper", 
        "style": "autumn", 
        "owner": "http://localhost:8000/users/2/", 
        "extra": "http://localhost:8000/snippetextras/1/"
    }
]}


HTTP GET /snippets?expand=owner
{
"count": 1, 
"next": null, 
"previous": null, 
"results": [
    {
        "url": "http://localhost:8000/snippets/1/", 
        "highlight": "http://localhost:8000/snippets/1/highlight/", 
        "title": "test", 
        "code": "def test():\r\n     pass", 
        "linenos": false, 
        "language": "Clipper", 
        "style": "autumn", 
        "owner": {
            "url": "http://localhost:8000/users/2/", 
            "username": "test", 
            "email": "test@test.com"
        }, 
        "extra": "http://localhost:8000/snippetextras/1/"
    }
]}
想知道如何在Sails.js或NodeJS中做到这一点吗?

您应该使用

以下是如何在
用户
模型和
代码段
模型之间创建一对多关联:

// User.js
module.exports = {
  // ...
  attributes: {
    // ...
    snippets: {
      collection: 'Snippet',
      via: 'owner'
    }
  }
};

// Snippet.js
module.exports = {
  // ...
  attributes: {
    // ...
    owner: {
      model: 'User'
    }
  }
};

然后,如果您需要代码段列表,可以点击
/snippets
,如果您需要有关代码段所有者的详细信息,可以点击
/snippets?populate=[owner]

谢谢Yand,这很有帮助。我真的想让它更深一层。我发现waterline存在这个问题,它只允许一个级别的扩展,并且有一个pull请求,希望它能升级到下一个版本。据我所知,在下一版本(v0.12)中未计划此操作。但是如果你真的想要的话,你可以创建你自己的控制器的动作和路线。好的,我来试一试。有什么可以帮我的吗?快看!