Sequelize Query to find all records that falls in between date range
The solution which works for me is this:-
// here startDate and endDate are Date objects
const where = {
from: {
$between: [startDate, endDate]
}
};
For reference to know more about operators:- http://docs.sequelizejs.com/en/latest/docs/querying/#operators
Note:
In MYSQL between
comparison operator is inclusive, which means it is equivalent to the expression (startDate <= from AND from <= endDate)
.
Try this condition what I think you are asking will do so.
For New Version Of Sequelize:
const where = {
[Op.or]: [{
from: {
[Op.between]: [startDate, endDate]
}
}, {
to: {
[Op.between]: [startDate, endDate]
}
}]
};
OR as your code structure:
const where = {
$or: [{
from: {
$between: [startDate, endDate]
}
}, {
to: {
$between: [startDate, endDate]
}
}]
};
For more info you can follow this Sequelize official documents
step - 1 require the Op from SEQUELIZE
const { Op } = require('sequelize');
step - 2 declare two constants :
const startedDate = new Date("2020-12-12 00:00:00");
const endDate = new Date("2020-12-26 00:00:00");
step - 3
table.findAll({where : {"fieldOfYourDate" : {[Op.between] : [startedDate , endDate ]}}})
.then((result) => res.status(200).json({data : result}))
.catch((error) => res.status(404).json({errorInfo: error}))