let params = JSON.parse(req.query.params);
let dateFrom = params.dateFrom;
let dateTo = params.dateTo;
dateFrom = dateFrom.replace(/T/g, ' '); //parse the data to the format accepted by mongodb
dateFrom = dateFrom.replace(/Z/g, ' ');
dateTo = dateTo.replace(/T/g, ' ');
dateTo = dateTo.replace(/Z/g, ' ');
productSchema.aggregate([
{
$match: {
productExist: true,
}
},
{
$match: {
productTimeStamp: {
$gte: dateTo,
$lte: dateFrom
}
}
},
{
$lookup:
{
from: 'supplierschemas',
localField: 'supplierId',
foreignField: '_id',
as: 'supplier'
}
},
{
$lookup:
{
from: 'brandschemas',
localField: 'brandId',
foreignField: '_id',
as: 'brand'
}
},
{
$lookup:
{
from: 'categoryschemas',
localField: 'categoryId',
foreignField: '_id',
as: 'category'
}
})]
I have the query above that gets data from mongodb using express. I want to select the 2 dates in between. But the code above is not working when I added these lines of codes:
{
$match: {
productTimeStamp: {
$gte: dateTo,
$lte: dateFrom
}
}
},
How excactly I can add these statement to get the data from 2 dates?
MongoDB default date is ISODate
. Do not do replace
on the dates.
Instead just pass them as new Dates:
let params = JSON.parse(req.query.params);
productSchema.aggregate([{
$match: {
productExist: true,
}
},
{
$match: {
productTimeStamp: {
$gte: new Date(params.dateFrom),
$lte: new Date(params.dateTo)
}
}
},
{
$lookup: {
from: 'supplierschemas',
localField: 'supplierId',
foreignField: '_id',
as: 'supplier'
}
},
{
$lookup: {
from: 'brandschemas',
localField: 'brandId',
foreignField: '_id',
as: 'brand'
}
},
{
$lookup: {
from: 'categoryschemas',
localField: 'categoryId',
foreignField: '_id',
as: 'category'
}
})]
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