dkx22
dkx22

Reputation: 1133

Waterline contains on association attributes?

I have a model which is populated with users. So I want to make a find where one of the users = someString.

So using Waterline I can do this

        Partie.find().populate('users').where({category:{'contains':'sport'}}).exec(function(e,r){
        console.log(r);
        res.json(200,r);
    });

But how do I make the contains on 'users'? Which is an array.

"users": [
  {
    "username": "firstUser",
    "createdAt": "2015-07-30T15:33:57.662Z",
    "updatedAt": "2015-07-30T15:33:57.662Z",
    "id": "55ba43e58cce9ee80865271b"
  },
  {
    "username": "someUsername",
    "createdAt": "2015-08-04T12:14:50.291Z",
    "updatedAt": "2015-08-04T12:14:50.291Z",
    "id": "55c0acba2d1502ed2faf2b3b"
  }
],...

Not sure if that's even possible. Feel free to suggest alternatives

Upvotes: 1

Views: 278

Answers (1)

Hless
Hless

Reputation: 3316

You can pass a second argument into populate with containing criteria for the query, eg:

 Partie.find().populate('users', {where: {username: "someUsername"}})...

In my experience (using latest waterline) the example above only populates users that match the given usernames into the Partie object.

However, on my machine it does NOT restrict what 'Parties' are returned from the search query (perhaps this has something to do with my waterline/postgres adapter version). I solved this issue by filtering the complete array after it returned (using lodash):

 res.json(_.filter(parties, function(party){
    // Pluck all usernames and check if 'someUserName' is attending this party
    return _.contains(_.pluck(party.users, 'username'), 'someUserName');
 }));

Note that using a filter like example above is inadvisable for large datasets!

Upvotes: 3

Related Questions