Mongoose Date Filter
I have data stored in a MongoDB database and I'm using Mongoose to query the data. I'm trying to run date queries against my data to return objects from the database that fall with
Solution 1:
Use the actual date object for your query, not string as you are doing presently. Because mongo stores dates wrapped with the ISODate
helper and the underlying BSON (the storage data format used by mongo natively) has a dedicated date type UTC datetime which is a 64 bit (so, 8 byte) signed integer denoting milliseconds since Unix time epoch, your query doesn't return anything as it will be comparing the date fields in mongo with an ISO formatted string.
So, drop the toISOString()
conversion and use the date object:
if (data.date) {
const date = new Date();
const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
date.setDate(date.getDate() - dateRange);
query.start = { $lte: date };
console.log(query);
}
Call.find(query, function (error, docs) {
if (error) callback(error, null);
callback(null, docs);
});
Better yet, you can use the momentjs plugin that has a very intuitive and easy datetime manipluation API. One method you can use is the subtract()
function to get the date object n
number of days ago:
if (data.date) {
const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
const date = moment().subtract(dateRange, "days");
query.start = { $lte: date };
console.log(query);
}
Call.find(query, function (error, docs) {
if (error) callback(error, null);
callback(null, docs);
});
Post a Comment for "Mongoose Date Filter"