'Node Js sequelize select query by month

Am new in Node Js, In my Node Js project am using sequelize ORM with MySql database.

This is my query i want to write select query by month.

This is my query SELECT * FROM cubbersclosure WHERE MONTH(fromDate) = '04'

Here fromDate field type is date

enter image description here

This my code:

var fromDate = '2019-04-01'
var fromDateMonth = new Date(fromDate);
var fromMonth = (fromDateMonth.getMonth()+ 1) < 10 ? '0' + (fromDateMonth.getMonth()+1) : (fromDateMonth.getMonth()+1);

CubbersClosure.findAll({
    where:{
        // select query with Month (04)... //fromMonth
    }
}).then(closureData=>{        
    res.send(closureData);
}).catch(error=>{
    res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});

Here fromMonth get only month from date, so i want to write code select query by month.



Solution 1:[1]

I'm not sure but what about try this?

where: {
  sequelize.where(sequelize.fn("month", sequelize.col("fromDate")), fromMonth)
}

Solution 2:[2]

for those of you looking for postgres, this is a somewhat hacky way to make this work (make sure to unit test this):

const results = await models.users.findAll({
   where: this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3)
});

you can also take this a step further and query multiple attributes like so:

const results = await models.table.findAll({
   where: {
     [Op.and] : [
        this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3),
        this.app.sequelize.fn('EXTRACT(day from "createdAt") =', 3),
     ]
   }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 obo20