How to selectively populate waterline associations via query param in sails.js
Asked Answered
M

1

16

By default, sails will populate all relationships within a model when it's corresponding API route is hit. Does anyone know if it's possible to toggle this functionality? If I'm working with a one-to-many association, I may not want to populate the association when doing a listing of all items for performance reasons. But when viewing a single item, it would be nice to complete the population.

For example, say one ticket can have many comments. I don't care about the comments when fetching a case listing but would be important when viewing a specific case. I took a guess at how it could function but it fails:

localhost:1337/tickets?populate=false

Update

I implemented the above functionality within balderdashy/sails#1695. The only change is that you selectively choose which associations to populate using:

localhost:1337/tickets?populate=[]          // Don't populate anything
localhost:1337/tickets?populate=[comments]  // Only populate comments

This would override whatever is defined for populate within your blueprint config.

Marnamarne answered 14/5, 2014 at 0:43 Comment(5)
Pretty sure population is not turned on by default, you have to implicitly write it in query, like User.findOne(user.id).populate('userFriends').exec(...) (just a small example out of my head)Percolate
That is true if you are using Waterline directly. What I'm referring to is populations from a request URL which is processed by Sails blueprints. In that case, population is on by default unless you specify otherwise in config/blueprints.js with populate = false.Marnamarne
Oh, I didn't think about blueprints, sorry. Well, you can make your own route to lead to your controller.action and return results of query depending on url GET parameters.Percolate
I agree with @IļjaGubins. I dont think there is any way to do this using blueprint routes. You will have to override them if you want to do thisVerulamium
@jason Your solution works great. You should write the details as an answer. Btw, ?populate=false works for me (using sails-mysql adapter)Gynecium
T
10

You just need to separate your assosiactions via comma, just like this:

localhost:1337/tickets?populate=comments,owner&SOME_OTHER_PARAMS
Travail answered 27/8, 2015 at 20:49 Comment(4)
Doesn't seem to work for me. It works if I'm looking at a single record tho: tickets/123?populate=commentsAllard
this is wrong. it should be something like this localhost:1337/tickets?populate=[comments,owner]&SOME_OTHER_PARAMSLandowska
@philip maybe it's changed in new versionTravail
what version were you guys usingBernardabernardi

© 2022 - 2024 — McMap. All rights reserved.