Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to Brookshelf ORM

aaronmoodie
October 15, 2015

Intro to Brookshelf ORM

A simple intro the the Bookshelf ORM that I gave at Brooklyn JS #24

aaronmoodie

October 15, 2015
Tweet

More Decks by aaronmoodie

Other Decks in Technology

Transcript

  1. - Backbone patterns - Knex queries and migrations - Some

    Docs (at the time) Bookshelf.js ✔
  2. var Track = bookshelf.Model.extend({ tableName: 'tracks', hasTimestamps: true, user: function()

    { return this.belongsTo('User'); } }); var Tracks = bookshelf.Collection.extend({ model: Track }); Models and Collections define relationship
  3. Saving and Updating // Create a new track new Track({'title':'Never

    Gonna Give You Up'}) .save() .then(function(track) { console.log(track.get('title')); }); // Update existing track new Track({'title':'Never Gonna Give You Up'}) .save({'artist':'Rick Astley'}, {patch: true}) .then(function(track) { console.log(track.get('title')); });
  4. Querying new Track({'title':'Never Gonna Give You Up'}) .fetch() .then(function(track) {

    console.log(track.get('title')); }) .catch(function(err) { console.log(err); }); Model Fetch on attribute catch promise errors
  5. Querying new Tracks() .query(function(qb) { qb.orderBy('created_at','DESC'); }) .fetch({withRelated: ['user']}) .then(function(tracks)

    { res.status(200).json(tracks); }); Collection Knex query builder related models as an array
  6. Querying Model with fetchAll() new Track() .query(function(qb) { qb.orderBy('created_at','DESC'); })

    .fetchAll({ withRelated: [ {'user': function(qb) { qb.column('id', 'username'); }}, 'votes', 'tags' ] }) .then(function(tracks) {}); ‘user’ mapped to query callback
  7. Model (extending) var Track = bookshelf.Model.extend({ // Model attributes },

    { getRecent: Promise.method(function() { return new Track() .query({ /* build query */ }) .fetchAll({ /* fetch params */ }) .then(function(tracks) { return tracks; }) }); } });