0

I have a model that has an attribute that is a collection association: Take for example, a User model below.

module.exports = {

  attributes: {
    pets: {
      collection: 'pet'
    }
  }
}

I am aware that I can add pets to a user instance with

user.pets.add(3);

But how could I replace any existing pets with a new group of pets??

DevX
  • 1,714
  • 2
  • 14
  • 17

2 Answers2

4

Ok I've been playing with the API and found an answer. The following call should update (set) the pets association for a single user. If there were existing pets, this approach would override them.

User.update({id:1}, {pets: [{id: 7}, {id: 8}]}).exec(cb);
DevX
  • 1,714
  • 2
  • 14
  • 17
1

You'd remove all the existing pets and create new ones. sails.js has no single special API function to do what you are trying to do, but it's pretty simple either way:

var newPets = [
  { name: 'fluffy', user: 1 },
  ...
];

Pet.destroy({ user: 1 })
  .then(function () {
    return _.map(newPets, Pet.create);
  })
  .then(function (pets) {
    // pets are "replaced"
  });

Or something like that.

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
  • 1
    Thanks for confirming there's no API for this. – DevX Mar 03 '15 at 02:48
  • Would really like something like user.pets.set([1,4,5]) to associate those 3 and only 3 pet record ids to the user instance. Same for user.pets.add([4,5,6]) to add multiple pets at once. – DevX Mar 03 '15 at 02:50