Sails Js populate with conditions

565 views Asked by At

I'm trying to multiple populate in sails js using sails-hook-deep-orm. I want to filter the province id. I am using the latest version of Sails and Node. And I using MySQL for database.

This is my model :

// Province.js
attributes: {
    name: {
      type: 'string',
      required: true
    },
    description: {
      type: 'string',
      required: false
    },
    cities: {
      collection: 'city',
      via: 'province'
    }
}

// City.js
attributes: {
    name: {
      type: 'string',
      required: true
    },
    description: {
      type: 'string',
      required: false
    },
    province: {
      model: 'province'
    },
    communities: {
      collection: 'community',
      via: 'city'
    }
}

// Community.js
attributes: {
    name: {
      type: 'string',
      required: true
    },
    description: {
      type: 'string',
      required: false
    },
    cities: {
      collection: 'city',
      via: 'province'
    }
}

I have try with :

Community.find()
  .populate('city.province', {'city.province.id' : 1});

Community.find()
  .populate('city.province', { where: { 'city.province.id': 1 } });

The code still not filtering. I Hope this case can be solved. Thank you :)

1

There are 1 answers

2
Matthieu Loos On

When you populate an association of your object, the name needs to be the name of the association in the parent object and not the name of the model you are referring to.

In your situation, Community has the association named 'cities'.

The next step is to filter the list of cities, this is the where statement as the second argument of the populate.

Community.find()
 .populate('cities', { 
    where: { 
      province: 1 
    }
  }
)