Everton Mendonça Everton Mendonça - 3 months ago 16
Node.js Question

Sails/Waterline: How to retrieve relations inside a relation?

I need to retrieve an object and also get the relations and nested relations.

So, I have the three models below:

User model:

module.exports = {

attributes: {
name: {
type: 'string'
},
pets: {
collection: 'pet',
via: 'owner',
}
}


Pet model:

module.exports = {
attributes: {
name: {
type: 'string'
},
owner: {
model: 'user'
},
vaccines: {
collection: 'vaccine',
via: 'pet',
}
}


Vaccine model:

module.exports = {
attributes: {
name: {
type: 'string'
},
pet: {
model: 'pet'
}
}


Calling
User.findOne(name: 'everton').populate('pets').exec(....)
I get the user and associated Pets. How can I also get the associated vaccines with each pet? I didn't find references about this in the official documentation.

Answer

I've ran into this issue as well, and as far as I know, nested association queries are not built into sails yet (as of this post).

You can use promises to handle the nested population for you, but this can get rather hairy if you are populating many levels.

Something like:

User.findOne(name: 'everton')
  .populate('pets')
  .then(function(user) {
    user.pets.forEach(function (pet) {
      //load pet's vaccines
    });
  });

This has been a widely discussed topic on sails.js and there's actually an open pull request that adds the majority of this feature. Check out https://github.com/balderdashy/waterline/pull/1052

Comments