Tutorial: 004 - Select - Ad-Hoc Mapping

004 - Select - Ad-Hoc Mapping

When selecting, both tables and columns can be mapped to alternate property names in the resulting normalized document. DataContext#from, FromAdapter#select, and From#join can be given TableMetaList~TableMeta objects to describe how columns and tables should be mapped. Building on the previous examples, the bike_shops table and columns can be aliased as follows:

'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
    // Map the "bike_shops" table to a property named "shops."
    .from({table: 'bike_shops', as: 'bs', mapTo: 'shops'})

    // "bikeShopID" will map to a property named "id," and "name" will map to
    // "shopName."
    .select(
      {column: 'bs.bikeShopID', mapTo: 'id'},
      {column: 'bs.name',       mapTo: 'shopName'}
    );

  // This is the query that will be executed.
  console.log('Query:');
  console.log(query.toString(), '\n');

  // Executing a query returns a promise.
  return query
    .execute();
}

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

And here's the result ($ node example/retrieve/adHocMapping.js):

Query:
SELECT  `bs`.`bikeShopID` AS `bs.bikeShopID`,
        `bs`.`name` AS `bs.name`
FROM    `bike_shops` AS `bs` 

Result:
{ shops: 
   [ { id: 1, shopName: 'Bob\'s Bikes' },
     { id: 2, shopName: 'Zephyr Cove Cruisers' },
     { id: 3, shopName: 'Cycle Works' } ] }
  

Note that it's also possible to define custom mappings at initialization time. Take a look at the tutorials in the Schema section for an example of how this can be done.