Search code examples
node.jsmongodbsails.jswaterlinesails-mongo

SailsJS Perform sorting on populate data


Here is my current event model:

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true,
            unique: true
        },
        client: {
            model: 'client',
            required: true
        },
        location: {
            model: 'location',
            required: true
        }
    }
};

The client Model:

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true,
            unique: true
        },
        address: {
            type: 'string'
        },
        clientContact: {
            model: 'user',
            required: true
        }
    }
};

So how do I implement sorting based on the client name and also have the skip and limit property(for pagination) to work along with it.

I tried using the following query:

Event.find({ id: ['583eb530902db3d926345215', '583eb6dd91b972ee26dd97b1'] },
           { select: ['name', 'client'] })
           .populate('client', { sort: 'name DESC' })
           .exec((err, resp) => resp.map(r => console.log(r.name, r.client)));

But this does not seem to do it.


Solution

  • Waterline doesn't support sorting a result by child records like this. If client was a collection of child records attached to an event, then your code would sort each of the returned Event record's populated client array by name, but I'm assuming in this case client is a singular association (i.e. model: 'client').

    If what you want is an array of Event records sorted by the name of their client, you can do it relatively easily using Lodash after you retrieve the records:

    var _ = require('lodash');
    
    Event.find(queryCriteria).populate('client').exec((err, resp) => {
      if (err) { /* handle error */ }
      var sortedRecords = _.sortBy(eventRecords, (record) => { return record.client.name; });
    });