Miroslav Saracevic
Miroslav Saracevic

Reputation: 1466

Sequelize order by column name

I am trying to order by column name in Sequelize

Here is my model

var Milestones = sequelize.define('milestones', {
  milestoneId: Sequelize.INTEGER,
  data: Sequelize.JSON,
  repository: Sequelize.STRING
});

Database is PostegreSql 9.5

var dialect = 'postgres',
    protocol = 'postgres';

var sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
  host: dbConfig.host,
  dialect: dialect,
  protocol: protocol,
  dialectOptions: {
    timeout: 30
  },
  pool: {
    max: 5,
    min: 0,
    idle: 30000,
    maxConnections: 5,
    maxIdleTime: 30
  },
  logging: false
});

Here is my query

models.Milestones.findAll({
      where: {
        repository: req.body.repository
      },
      order: 'milestoneId'
    }).then(function (values) {
      // do something
    });

Here is my error

Unhandled rejection SequelizeDatabaseError: column "milestoneid" does not exist

So problem is that I wanna order by milestoneId but Sequelize is actually trying to order by milestoneid (notice the lack of camel case).

If I change to order by repository everything works, so the issue at this point seems to be related to the conversion to lowercase by Sequelize.

Any suggestions other than to rename the column in database to lowercase?

Thank you

Upvotes: 0

Views: 2532

Answers (2)

Aethyn
Aethyn

Reputation: 705

I had a similar issue with PostGreSQL and Oracle (with Sequelize-Oracle). Sequelize automatically adds quotes for many parameters.

Do you have "quoteIdentifiers" option turned off ? (default is on).

Maybe the problem isn't :
- order by milestoneid or order by milestoneId
But instead it can be :
- order by 'milestoneid' (with quotes causing the issue).

The doc says :

[options.quoteIdentifiers=true] : Boolean, Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them.

Upvotes: 0

MentalRay
MentalRay

Reputation: 344

Update your model with a field and it will be fine

var Milestones = sequelize.define('milestones', {
  milestoneId: {
    type: Sequelize.INTEGER,
    field: 'milestoneId'
  },
  data: Sequelize.JSON,
  repository: Sequelize.STRING
});

EDIT:

also update the ordering with

order: ['milestoneId']

Upvotes: 1

Related Questions