Edit Page

.addToCollection()

Add one or more existing child records to the specified collection (e.g. the comments of BlogPost #4).

await Something.addToCollection(parentId, association)
.members(childIds);

Usage

#
Argument Type Details
1 parentId Number or String The primary key value(s) (i.e. ids) for the parent record(s).
Must be a number or string (e.g. '507f191e810c19729de860ea' or 49).
Alternatively, an array of numbers or strings may be specified (e.g. ['507f191e810c19729de860ea', '14832ace0c179de897'] or [49, 32, 37]). In this case, all of the child records will be added to the appropriate collection of each parent record.
2 association String The name of the plural ("collection") association (e.g. "pets").
3 childIds Array The primary key values (i.e. ids) of the child records to add. Note that this does not create these child records, it just links them to the specified parent(s).
Errors
#
Name Type When?
UsageError Error Thrown if something invalid was passed in.
AdapterError Error Thrown if something went wrong in the database adapter.
Error Error Thrown if anything else unexpected happens.

See Concepts > Models and ORM > Errors for examples of negotiating errors in Sails and Waterline.

Example

#

For user 3, add pets 99 and 98 to the "pets" collection:

await User.addToCollection(3, 'pets')
.members([99,98]);

If either user record already has one of those pets in its "pets", then we just silently skip over it.

Edge cases

#

Notes

#
  • If the association is "2-way" (meaning it has via) then the child records will be modified accordingly. If the attribute on the other side is singular, then each child record's foreign key will be changed. If it's plural, then each child record's collection will be modified accordingly.
  • In addition, if the via points at a singular ("model") attribute on the other side, then .addToCollection() will "steal" these child records if necessary. For example, imagine you have an Employee model with this plural ("collection") attribute: involvedInPurchases: { collection: 'Purchase', via: 'cashier' }. If you executed Employee.addToCollection(7, 'involvedInPurchases', [47]) to assign this purchase to employee #7 (Dolly), but purchase #47 was already associated with a different employee (e.g. #12, Motoki), then this would "steal" the purchase from Motoki and give it to Dolly. In other words, if you executed Employee.find([7, 12]).populate('involvedInPurchases'), Dolly's involvedInPurchases array would contain purchase #47 and Motoki's would not.

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Reference

Reference