0

How to get the total number of records for the current day? I get 0 as a result, although I have a couple of entries.

module.exports.getOnline = async function (req, res) {
    try {
        var current_date = new Date().toISOString()
        const online = await Online.find({ Date: current_date })
        res.status(200).json(online.length)
    } catch (e) {
        errorHandler(res, e)
    }
}

2 Answers2

1

I think that currently you are searching for records with a specific date and time. Try to look for a range of dates, with today at 00:00 and today at 23:59.

This one might help:

https://stackoverflow.com/a/2943685/12647796

edit - I tried to match it to your problem

var min_date = new Date();
var max_date = new Date();
min_date.setHours(0,0,0,0);
max_date.setHours(23,59,59,999);
const online = await Online.find({
    Date: {
        $gte: min_date,
        $lt: max_date
    }
})
res.status(200).json(online.length)
avivc411
  • 24
  • 5
1
var current_date = new Date().toISOString()

The toISOString() method converts a Date object into a string, using the ISO standard. The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ

so when you get the current date and using this method it will not match with the existing records in database.that's why query return 0.

if you want to get the current day records you need to use following code for getting current date,month and year than use it for query.

module.exports.getOnline = async function (req, res) {
try {
    var d = new Date();

var date = d.getDate();
var month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
var year = d.getFullYear();
 
var dateStr = date + "/" + month + "/" + year;
    
    const online = await Online.find({ Date: dateStr })
    res.status(200).json(online.length)
} catch (e) {
    errorHandler(res, e)
}
}

I think this will help you.

Hammad Ali
  • 331
  • 3
  • 12