Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MAX(id) GROUP BY other_field with Sequalize.js?

I've got a MySQL database which stores prices for certain products which are represented by symbols. I now want to get the latest price for each symbol. In pure MySQL I can run the following:

SELECT *
FROM prices
WHERE id IN (SELECT MAX(id) FROM prices GROUP BY symbol);

I now want to do the same using Sequelize.js. So I tried several variations of the following:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('mmjs', 'root', 'xxx', {host: 'localhost', dialect: 'mysql', logging: false, pool: {max: 5, min: 1, idle: 20000, acquire: 30000, handleDisconnects: true}, operatorsAliases: false,});

const Price = sequelize.define('price', {
    createdAt: {type: Sequelize.DATE(6), allowNull: false},
    symbol: {type: Sequelize.STRING, allowNull: false},
    bid: {type: Sequelize.FLOAT},
    ask: {type: Sequelize.FLOAT},
});

Price.findAll({
    attributes: [Sequelize.fn('max', Sequelize.col('id'))],
    group: ["symbol"]
}).then((maxIds) => {
    console.log(maxIds);
    console.log(maxIds.length);  // logs the correct length of 82
    return Price.findAll({
        where: {
            id: {
                [Sequelize.Op.in]: maxIds
            }
        }
    });
}).then(maxPrices => {
    console.log(maxPrices);
});

As said in the comment the maxIds.length logs the correct length of 82. But after that I get an error saying Unhandled rejection Error: Invalid value price. Furthermore, the console.log(maxIds); gives me some objects which seem to be empty of the expected max id value which I'm expecting. Below is an example of one such an object.

What am I doing wrong here? Why doesn't it give me the max ids just like the query SELECT MAX(id) FROM prices GROUP BY symbol?

price {
    dataValues: {},
    _previousDataValues: {},
    _changed: {},
    _modelOptions:
     { timestamps: true,
       validate: {},
       freezeTableName: false,
       underscored: false,
       underscoredAll: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: [],
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Object],
       hooks: {},
       uniqueKeys: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Array] },
    __eagerlyLoadedAssociations: [],
    isNewRecord: false },
like image 734
kramer65 Avatar asked Oct 20 '25 02:10

kramer65


1 Answers

Sequelize is trying to map result to Price model - use raw: true to prevent that.

Price.findAll({
    attributes: [Sequelize.fn('max', Sequelize.col('id'))],
    group: ["symbol"],
    raw: true,
})
like image 179
m1ch4ls Avatar answered Oct 21 '25 17:10

m1ch4ls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!