Search code examples
node.jssequelize.js

Get yesterday's data without using Sequelize literal


Happy new year!

What I want to do is get previous day's total sales amount from MySql database. My current code is using Sequelize.literal. But, I think it is a little bit ugly. Is there any nice way to query the data without Sequelize.literal?

Thanks in advance!

p/s. I don't want to use mement.js

// My Current Code

const Sequelize = require('sequelize')
const { Op } = require('sequelize')


const getSalesAmount = async () => {

    const grand = await CoreOrder.sum('grandTotal', {
        where: {
            orderState: {
                [Op.not]: 'incomplete'
            },
            createdAt: Sequelize.literal('CURDATE() - INTERVAL 1 DAY')
        }
    })
}

Solution

  • You need to get yesterday date either in JS code (using datetime libs like moment.js) or by DB (using a datetime function like ADDDATE):

    const grand = await CoreOrder.sum('grandTotal', {
      where: {
        orderState: {
          [Op.not]: 'incomplete'
       },
       createdAt: Sequelize.fn('ADDDATE', Sequelize.fn('CURDATE'), -1)
     }
    })
    

    If using Sequelize.fn instead of Sequelize.literal really helps you then that's it, though I'd personally pass the constant date to Sequelize calculating it in the code to keep Sequelize query as simple as possible.