I am building a "filtering" system and I need to query users in the collection whose date of birth dates are between 2 dates.
The code I have right now looks like:
if (req.query.ageMin) {
var dobMin = new Date(dateNow.setFullYear(dateNow.getFullYear() - req.query.ageMin));
}
if (req.query.ageMax) {
var dobMax = dateNow.setFullYear(dateNow.getFullYear() - req.query.ageMax);
}
if (dobMin && dobMax) {
query.dob = {
$gte: dobMin,
$lt: dobMax
}
} else if (dobMin) {
query.dob = {
$gte: dobMin
}
} else if (dobMax) {
query.dob = {
$lt: dobMax
}
}
db.users.find(query).toArray(function (err, users) {
console.log(users);
});
An empty array is returned (no error). I assume it's because the date in the collection are not a date object -- they are simply strings for example "1980-06-15". Is there any option I can pass to the query so that Mongo makes the stored date a date object when querying it? Or any solution for that matter...
Try converting the date instances to strings:
dobMin = dobMin.toISOString().substring(0, 10)
dobMax = dobMax.toISOString().substring(0, 10)