Updating association in Sails

时间:2015-05-24 21:52:32

标签: sails.js

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?

1 个答案:

答案 0 :(得分:1)

使用blueprints API更新模型有两个选项:

  1. 将数据作为发布请求的正文发送。将数据作为请求正文中的json对象发送
  2. Post /person/1 body: { "books": [1002,1003]}

    1. 覆盖蓝图更新方法
    2. 添加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);
          });
        });
      }