is it possible to define a default sort order for a sequelize model

Viewed 3315

I'm looking for a way to define a default sort order for a model in sequelize so that records always come back alphabetically sorted on a given field, for example - something like a user model that has a 'name' field, I'd like the users to be sorted alphabetically by default when I do User.findAll().

This question is NOT about how to define the sort order in the findAll options, I already know how to do that:

User.findAll({ order: [['name', 'ASC']] })

I want something like the rails default sort order:

class User < ActiveRecord::Base
  default_scope { order(name: :desc) }
end

I have to admit, I haven't read the sequelize docs in detail, which I'm doing now, but if someone can point it out in the meantime

1 Answers

TL;DR

a default scope can be applied to a model, something along these lines:

MyGreatModel.addScope('defaultScope', {
  order: [['id', 'ASC']],
}, { override: true })

I've found 2 very useful resources to answer my question, first, the sequelize docs about scopes and I knew to look for this from an answer on this github issue

Related