skip to Main Content

I need to get data from my MongoDB using Nodejs API . I trying this

 const attendanceRecords = await Attendence.find({
      user: _id,
      currentDate: { $gte: fromDate, $lte: toDate },
    }).populate("user", "firstname lastname email");

But its not giving me correct data

currentDate field in my MongoDB database is date datatype and i am storing this date using this code

const mycurrentDate = new Date().toLocaleDateString('en-US', {
    day: '2-digit',  
    month: '2-digit',
    year: 'numeric',
 });
 
 const formattedDate = new Intl.DateTimeFormat("en-US", optionss).format(date); 

the datatype of formattedDate is string Now how can I filter data and get data between a range of two dates ?

2

Answers


  1. Assume using Mongoose with node, the query will be like that!

    > var startDate = new Date("2023-01-01");
    var endDate = new Date("2023-12-31");
    
    Modal_name.find({
      date_field_name: {
        $gte: startDate,
        $lte: endDate
      }
    });
    

    date_field_name your created_at field name in Collection

    Login or Signup to reply.
  2. This error is likely caused by trying to store Date type as string type and filtering them as Date type during the query. 

    const mycurrentDate = new Date(); // when you store to mongodb you should use Date type
    
    let fromDate = new Date('2023-06-22'); // use Date type to filter
    let toDate = new Date('2023-06-31'); // Date type
    const attendanceRecords = await Attendence.find({
          user: _id,
          currentDate: { $gte: fromDate, $lte: toDate },
        }).populate("user", "firstname lastname email");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search