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 within the specified data-range.
My webform sends an API request to an external micro-service/api that is responsible for querying the data in the Mongo database. The API receives a single value that is representative of a number of days. eg: date: "7d". I then proceed to build the mongoose query like so:
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.toISOString() };
console.log(query);
}
and an example date from my database is:
start: 2016-02-10T09:09:01.000Z
The query is then executed:
Call.find(query, function (error, docs) {
if (error) {
callback(error, null);
} else {
callback(null, docs);
}
});
and finally, an example of query:
{ approved: 1, start: { '$lte': '2016-02-09T14:24:29.115Z' } }
However, no matter what date I send to my API the response is always empty...
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With