Search code examples
node.jsmongodbsails.jswaterline

Sails.js: How to find records based on values in associated collection?


I'm looking for a way to make sub-query using Sails.js Waterline. The record has an association with Charge model.

I would expect something like that to work, but that doesn't seem to be supported:

var topRecords = await Record.find({'charge.paid':true});

The closest I got was this:

var topRecords = await Record.find().populate('charge',{paid:true});

but the problem is that it still returns all the Records regardless, just doesn't populate the records that do not match populate where statement.

The reason why I can't search for charges first is that I want to sort the data based on one of the values in Record.


Solution

  • You can fetch the Charges then use .map to get the records from there.

    const topCharges = await Charge.find({ paid: true }).populate('records');
    const topRecords = topCharges.map(charge => charge.record);