Skip to content

Instantly share code, notes, and snippets.

@dpatlut
Created November 23, 2020 22:56
Show Gist options
  • Save dpatlut/5e6f62f54b612b2ffea62643f877d7c2 to your computer and use it in GitHub Desktop.
Save dpatlut/5e6f62f54b612b2ffea62643f877d7c2 to your computer and use it in GitHub Desktop.
Express/Seq. Rounding Out

Day 10: Express Custom Error Handling, Eager Loading with Sequelize

Credit: Noelle Laureano

You should be able to:

  • Write custom error handlers in Express
  • Utilize eager loading in Sequelize queries
  • Write class and instance methods on Sequelize models

In your own words, what is eager loading?

  • The equivalent to doing an LEFT JOIN in SQL.
    • By default it does a LEFT JOIN. However, you can indicate to Sequelize what kind of join you want to do. Below is from the Sequelize Documentation, which is linked below this snippet.
User.findAll({
    include: [{
    model: Task // will create a left join
   }]
});
User.findAll({
  include: [{
    model: Task,
    right: true // will create a right join
  }]
});
User.findAll({
  include: [{
    model: Task,
    required: true // will create an inner join
  }]
});
  • Reference:
    • Sequelize: Eager Loading

      As briefly mentioned in the associations guide, eager Loading is the act of querying data of several models at once (one 'main' model and one or more associated models). At the SQL level, this is a query with one or more joins).

      When this is done, the associated models will be added by Sequelize in appropriately named, automatically created field(s) in the returned objects.

      In Sequelize, eager loading is mainly done by using the include option on a model finder query (such as findOne, findAll, etc).

      // Models
      const User = sequelize.define('user', { name: DataTypes.STRING }, { timestamps: false });
      const Task = sequelize.define('task', { name: DataTypes.STRING }, { timestamps: false });
      const Tool = sequelize.define('tool', {
        name: DataTypes.STRING,
        size: DataTypes.STRING
      }, { timestamps: false });
      
      // Associations
      User.hasMany(Task);
      Task.belongsTo(User);
      User.hasMany(Tool, { as: 'Instruments' }); // **aliased**
      
      // Eager Loading examples:
      
      // (1) Fetching a single associated element (i.e. include each task's user)
      const tasks = await Task.findAll({ include: User });
      
      // Sample output:
      [{
        "name": "A Task",
        "id": 1,
        "userId": 1,
        "user": {
          "name": "John Doe",
          "id": 1
        }
      }]
      
      // (2) Fetching all associated elements (i.e. include all of the users' tasks)
      const users = await User.findAll({ include: Task });
      
      // Sample output:
      [{
        "name": "John Doe",
        "id": 1,
        "tasks": [{
          "name": "A Task",
          "id": 1,
          "userId": 1
        }]
      }]
      
      // (3) Fetching an Aliased association (i.e. include each user's tools [aka "instruments"])
      // If an association is aliased (using the as option), you must specify this alias when including the model. Instead of passing the model directly to the include option, you should instead provide an object with two options: model and as.
      const users = await User.findAll({
        include: { model: Tool, as: 'Instruments' }
      });
      
      // Sample output:
      [{
       "name": "John Doe",
       "id": 1,
       "Instruments": [{
         "name": "Scissor",
         "id": 1,
         "userId": 1
       }]
      }]
    • FSA Sequelize docs: Joins/Includes (aka "Eager Loading")
      • Note: FSA Sequelize docs are deprecated (e.g. findById --> findByPk)

Which of the following is a valid error-handling middleware?

What does this refer to in this code snippet? User.findByBirthday = function() { return this; }

What does this refer to in this code snippet? User.prototype.getBirthday = function() { return this; }

Any other questions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment