3

I want to sort a sequelize query by a nested attribute of a JSONB object.

I have a model like that:

sequelize.define('product', {
    available: { type: Sequelize.BOOLEAN },
    price: { type: Sequelize.JSONB },
    ...
}

where price is kind of this:

price = {
    EUR: 1.2,
    CHF: 1.3,
}

I want to sort a findAll query by price.EUR. I hoped that this works:

product.findAll({ where: { available: true }, order: [['price.EUR', 'ASC']] }

But I get an unsorted array.

The underlying DB is postgres.

A solution is to sort the result programmatically in javascript (array._prototype.sort()). But I wonder if it is possible with a sequelize query.

1 Answer 1

2

try this:

roduct.findAll({ where: { available: true }, order: [[sequelize.literal('price->>\'EUR\''), 'ASC']] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.