Attributes

To select only some attributes, you can use the attributes option. Most often, you pass an array:

  1. Model.findAll({
  2. attributes: ['foo', 'bar']
  3. });
  1. SELECT foo, bar ...

Attributes can be renamed using a nested array:

  1. Model.findAll({
  2. attributes: ['foo', ['bar', 'baz']]
  3. });
  1. SELECT foo, bar AS baz ...

You can use sequelize.fn to do aggregations:

  1. Model.findAll({
  2. attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
  3. });
  1. SELECT COUNT(hats) AS no_hats ...

When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with instance.get('no_hats').

Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:

  1. // This is a tiresome way of getting the number of hats...
  2. Model.findAll({
  3. attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
  4. });
  5. // This is shorter, and less error prone because it still works if you add / remove attributes
  6. Model.findAll({
  7. attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }
  8. });
  1. SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...

Similarly, it's also possible to remove a selected few attributes:

  1. Model.findAll({
  2. attributes: { exclude: ['baz'] }
  3. });
  1. SELECT id, foo, bar, quz ...