* .add( primary key )

Purpose

Used to add records to the join table that is automatically generated during a Many-to-Many association. It accepts either the primary key of the model instance (defaults to record ID) or a new record (object) that you want created and to be associated with.

Overview

Parameters

Description Accepted Data Types Required ?
1 Records {}, string, int Yes

Example Usage

  1. User.find({name:'Mike'}).populate('pets').exec(function(e,r){
  2. r[0].pets.add(7);
  3. r[0].save(function(err,res){
  4. console.log(res);
  5. }
  6. });
  7. /*
  8. { pets:
  9. [ { name: 'Pinkie Pie',
  10. color: 'pink',
  11. id: 7,
  12. createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
  13. updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) },
  14. { name: 'Rainbow Dash',
  15. color: 'blue',
  16. id: 8,
  17. createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
  18. updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) },
  19. { name: 'Applejack',
  20. color: 'orange',
  21. id: 9,
  22. createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
  23. updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) } ],
  24. name: 'Mike',
  25. age: 16,
  26. createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
  27. updatedAt: Wed Feb 12 2014 19:30:54 GMT-0600 (CST),
  28. id: 7 }
  29. */

Notes

  • .add() does not accept arrays of any kind. Don’t try it.
  • Any string arguments passed must be the primary key of the record.
  • .add() alone won’t actually persist the change in associations to the databse. You should call .save() after using .add() or .remove().