Sails.js:如何使用模型关联来填充数组

我正在使用“sails”:“〜0.10.0-rc5”,“sails-mongo”:“^ 0.10.0-rc3”。 我有2个模型:发票,项目。

发票模型

Invoice: { name: 'sample 1', items: [1,2] // 1,2 is id of Item model } 

项目模型

 Item { id: 1, name: "king" } Item { id: 2, name: 'queen' } 

我想要的结果是:

 Invoice: { name: 'sample 1', items: [{ id: 1, name: "king" }, { id: 2, name: 'queen' }] } 

我从帆文件中读取模型协会,但我不知道如何使用它在我的情况。

您的物品模型将如下所示:

 attributes: { name: "STRING" // You don't need the ID field as this is automatically created for you } 

您的发票模型将如下所示:

 attributes: { name: "STRING" items: { collection: "item", via: "item" } } 

现在创build一些项目模型的文档。

 sails> ModelNameOfItem.create({name:'MyFirstItem'}).exec(console.log) null { name: 'MyFirstItem', createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST), updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST), _id: "some_id_created_by_mongo" } 

现在创build发票模型的文档。

 sails> ModelNameOfInvoice.create({name:'MyFirstInvoice', items:"the_id from_item_created"}).exec(console.log) null { name: 'MyFirstInvoice', createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST), updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST), _id: "some_id_created_by_mongo" } 

就这样! 要查询这个,使用populate方法。

 sails> Invoice.find({name:'MyFirstInvoice'}).populate('items').exec(console.log); 

正确的答案是:在发票模型中:

 ... items: { collection: 'item' }