Tutorial: 005 - Select - Ordering

005 - Select - Ordering

The results of a query can be ordered using the Select#orderBy method. In its simplest form, this variadic method can be passed multiple strings that correspond to fully-qualified columns names. Or, to change the order direction, objects can be supplied.

'use strict';

const MySQLDriver = require('node-data-mapper-mysql').MySQLDriver;
const driver      = new MySQLDriver(require('../bikeShopConOpts.json'));

driver
  .initialize()
  .then(runQuery)
  .then(printResult)
  .catch(console.error)
  .finally(() => driver.end());

function runQuery(dataContext) {
  const query = dataContext
    .from('staff s')
    .select('s.staffID', 's.hasStoreKeys', 's.firstName')
    .orderBy({column: 's.hasStoreKeys', dir: 'DESC'}, 's.firstName');

  console.log('Query:');
  console.log(query.toString(), '\n');

  return query
    .execute();
}

function printResult(result) {
  console.log('Result:');
  console.log(result);
}
  

Here's the generated query and execution result ($ node example/retrieve/order.js):

Query:
SELECT  `s`.`staffID` AS `s.staffID`,
        `s`.`hasStoreKeys` AS `s.hasStoreKeys`,
        `s`.`firstName` AS `s.firstName`
FROM    `staff` AS `s`
ORDER BY `s`.`hasStoreKeys` DESC, `s`.`firstName` ASC 

Result:
{ staff: 
   [ { staffID: 4, hasStoreKeys: , firstName: 'Abe' },
     { staffID: 2, hasStoreKeys: , firstName: 'John' },
     { staffID: 5, hasStoreKeys: , firstName: 'Sal' },
     { staffID: 6, hasStoreKeys: , firstName: 'Valerie' },
     { staffID: 7, hasStoreKeys: , firstName: 'Kimberly' },
     { staffID: 8, hasStoreKeys: , firstName: 'Michael' },
     { staffID: 1, hasStoreKeys: , firstName: 'Randy' },
     { staffID: 3, hasStoreKeys: , firstName: 'Tina' } ] }