Tutorial: 015 - Update - Update a Single Model

015 - Update - Update a Single Model

A model is updated using the DataContext#update method, which takes a single object as a parameter. Each propperty of the model should map to a table, and the associated value should be one or more models--an object or an array--containing at least the model's primary key.

Below is an example ($ node example/update/updateSingleModel.js) that updates a single bonuses record by ID. The example's output 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) {
  // Update a single model by ID.
  const query = dataContext
    .update({
      bonuses: {
        // The primary key is required when updating a model.
        bonusID: 3,
        amount:  600,
        reason:  'Super outstanding technical skills.'
      }
    });

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

  return query
    .execute();
}

function printResult(result) {
  // The result object will contain an affectedRows property, which is an
  // integer that that reflects the number of updated records.
  console.log('Result:');
  console.log(result);
}
  
Query:
UPDATE  `bonuses` AS `bonuses`
SET
`bonuses`.`amount` = :bonuses_amount_1,
`bonuses`.`reason` = :bonuses_reason_2
WHERE   (`bonuses`.`bonusID` = :bonuses_bonusID_0) 

Result:
{ affectedRows: 1 }