user3487954
user3487954

Reputation: 21

Sails.js: how to populate array using model associations

I'm using "sails": "~0.10.0-rc5", "sails-mongo": "^0.10.0-rc3". I have 2 models: Invoice, Item.

Invoice model

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

Item model

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

I want the result to be:

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

I read model associations from the sails docs but i don't know how to use it in my situation.

Upvotes: 1

Views: 5150

Answers (2)

Thịnh Phạm
Thịnh Phạm

Reputation: 2673

The right answer is: in invoice model:

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

Upvotes: 1

aludvigsen
aludvigsen

Reputation: 5991

Your item model will look like this:

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

Your invoice model will look like this:

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

Now create a few documents of the item model.

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

Now create a document of the invoice model.

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

Thats all! To query this, use the populate method.

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

Upvotes: 1

Related Questions