Filtering Sails.js request model by collection attribute

Suppose I have the following models in Sails.js v0.10:

Person.js

module.exports = {

  attributes: {

    name: 'string',

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

  } 
};

Book.js

module.exports = {

  attributes: {

    name: 'string',

    person: {
      model: 'person'
    }

  } 
};

      

I want the query to return an array of people who have a specific linked book. I would like to do something like the following request, but I don't know how:

  Person.find()
    .populate('books')
    .where({ books.name: 'Game of Thrones'})
    .exec(function(err, person) {
      if (err) return res.send(err, 500);
      res.json(person);
    });

      

Any ideas if it's possible to do this using a simple query?

+3


source to share


1 answer


First, you need to configure your model Book

to make it a many-to-many relationship:

module.exports = {

  attributes: {

    name: 'string',

    people: {
      collection: 'person',
      via: 'books'
    }

  } 
};

      



Querying the properties of an association is currently not possible with Sails, although it is in the roadmap. But once you've set up your model Book

as above, you can get what you want by querying in reverse:

Book.findOne({name: 'Game of Thrones'}).populate('people').exec(...);

      

+1


source







All Articles