Intro to Brookshelf ORM

Intro to Brookshelf ORM

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

537d8040116ce1a24c6947db7bee209e?s=128

aaronmoodie

October 15, 2015
Tweet

Transcript

  1. Hello! I’m Aaron Moodie, a product designer at Etsy. I

    like JavaScript.
  2. A quick overview of Bookshelf.js, an ORM for Node.

  3. slime.io

  4. Bookshelf? Node ORM2 Sequelize? Node ORM?

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

    Docs (at the time) Bookshelf.js ✔
  6. Model & Collections

  7. 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
  8. Saving and Updating

  9. 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')); });
  10. Queries

  11. 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
  12. 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
  13. 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
  14. 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; }) }); } });
  15. router.get('/tracks', function(req, res, next) { Track.getRecent() .then(function(tracks) { res.status(200).send(JSON.stringify(tracks)); })

    .catch(function(err) { return next(err); }); }); Much cleaner
  16. - Knex migrations - Awesome Docs - Active updates More

    Bookshelf Goodness
  17. Thanks! @aaronmoodie