I need to filter the "incomers" based on age, but in the table I only have the date of birth. I need people between the minimum and maximum age, how can I do it?
router.post('/', function (req, res, next) {
let parameters = JSON.parse(req.body.parameters);
parameters.states = parameters.states.split();
parameters.species = parameters.species.split();
model.person.findAll({
where: {
uf: parameters.states,
species: parameters.species,
dateBirth: BETWEEN PARAMETERS.MINAGE AND PARAMETERS.MAXAGE
}
})
.then(person => res.json({
error: false,
data: person
}))
.catch(error => res.json({
error: true,
data: [],
error: error
}));
});
You can use the between
operator:
model.person.findAll({
where: {
uf: parameters.states,
species: parameters.species,
dateBirth: {
[Op.between]: ['2000-01-01', '2020-01-01'],
}
}
})
You can use it like :
var startAge = 18;
var endAge = 20;
var today = moment();
var startDate = today.subtract('years', startAge);
var endDate = today.subtract('years', endAge);
model.person.findAll({
where: {
uf: parameters.states,
species: parameters.species,
dateBirth: : {
$between: [startDate, endDate]
}
}
})
You can use Raw queries in your where something like -
var Sequelize = require("sequelize");
var now = '2010-01-01';//Current Date
model.person.findAll({
where: Sequelize.literal('( (ud IN ('+parameters.states+')) AND (species IN ('+parameters.species+')) AND ((DATE_FORMAT(FROM_DAYS(DATEDIFF(dob,'+now+')), "%Y")+0) BETWEEN '+minDate+' AND '+maxDate+') )')
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.