windchime
windchime

Reputation: 1285

Updating association in Sails

I am using SailsJs. Two models exist. Model 'person' contains the following attribute:

books: {
  collection: 'book',
  via: 'owner'
},

Model 'book' contains:

owner: {
  model: 'person'
},

When I create an instance of person, I can use http request and simply put something like the following

Post /person?books=1001,1002

As long as 1001 and 1002 are valid ids of book, it works.

However, when I try to person's books attribute, this does not work

Post /person/1?books=1002,1003

books of person with id 1 becomes empty.

But,

Post /person/1?books=1002

would work.

Why is this? How can I modify collection attribute?

Upvotes: 2

Views: 343

Answers (1)

Ofer Herman
Ofer Herman

Reputation: 3068

There are 2 options to update a model using the blueprints API:

  1. Send the data as the body of the post request. send the data as a json object in the request body

Post /person/1 body: { "books": [1002,1003]}

  1. Override the blueprint update method

Add this the PersonController.js:

update: function (req, res) {
  Person.findOne(req.param('id')).populate('books').exec(function (err, person){
    if (err) { 
      sails.log.error(err);
      return;
    }
    var books = req.param('books').split(',').map(function (book){return parseInt(book);}),
      booksToRemove = _.difference(person.books.map(function(book) {return book.id;}), books);

    // Remove books that are not in the requested list
    person.books.remove(booksToRemove);
    // Add new books to the list
    person.books.add(books);
    person.save(function (err, r) {;
      res.json(r);
    });
  });
}

Upvotes: 1

Related Questions