Home > Enterprise >  Query monthly data in nodejs mongoose
Query monthly data in nodejs mongoose

Time:01-04

  const getDate = req.query.month;
  const datas = await Attendance.find().populate("user", "firstName lastName");

I want to get only this month data or any month data in nodejs

NB: getDate = 2023-01-03T14:53:28.096Z

CodePudding user response:

 // get query
    const getDate = req.query.month;
    const date = new Date(getDate);

    // get first and last day of month
    const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    const lastDay = new Date(date.getFullYear(), date.getMonth()   1, 0);

    // query
    const datas = await Attendance.find({ createdAt: { $gt: firstDay, $lt: lastDay } }).populate("user", "firstName lastName");

CodePudding user response:

if you want to get data depends on specific month it will be like

  const month = req.query.month;
  const datas = await Attendance.find({ "$expr": { "$eq": [{ "$month": "$createdAt" }, month] }}).populate("user", "firstName lastName")
  • Related