Search code examples
rethinkdbrethinkdb-javascript

sort nested timestamps in a query


I need to make a query with a list of Incidents and his nested events ordered DESC by his startedAt and timestamp dates. By default ReQL give the dates with a ASC order. I've got the folowing structure: { "id": "87e14db8-1e15-4718-baac-f1c785e985cb" , "title": "Connection Error" "startedAt": Mon Oct 26 2015 14:33:00 GMT+00:00 , "events": [{ "message": "Cannot connect to theserver.com", "timestamp": Mon Oct 26 2015 14:33:00 GMT+00:00 },{ "message": "Cannot connect to theserver.com," "timestamp": Mon Oct 26 2015 14:33:20 GMT+00:00 },{ "message": "Cannot connect to theserver.com", "timestamp": Mon Oct 26 2015 14:33:40 GMT+00:00 }] },{ "id": "87e14db8-1e15-4718-baac-f1c785e985cb" , "title": "Other Connection Error" "startedAt": Mon Oct 26 2015 14:34:20 GMT+00:00 , "events": [{ "message": "Connection rejected", "timestamp": Mon Oct 26 2015 14:34:20 GMT+00:00 },{ "message": "Connection rejected", "timestamp": Mon Oct 26 2015 14:34:41 GMT+00:00 }] },{ ... (several more) }

If I run r.db('mydb').table('Incident').orderBy(r.desc('createdAt')), the Incident's are ordered by createdAt as espected. But the nested eventsare still ordered ASC.

How can I make a query in order to get the nested events with a DESC order by timestamp?


Solution

  • Something like this should do it:

    r.table('Incident').orderBy(r.desc('createdAt')).merge(function(row) {
      return {events: row('events').orderBy(r.desc('timestamp'))};
    })