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

我是NodeJS和Sails.js的新手。

我想创build一个REST API,允许我扩展基于查询参数的资源。 例如

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模型和Snippet模型之间创build一对多关联的方法:

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

那么如果你需要一个片段列表,你可以点击/snippets ,然后点击/snippets?populate=[owner]如果你需要关于片段所有者的详细信息。