Axios获取带有参数的请求以过滤查找certrain createdAt range in mongodb

nhaq1z21  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(162)

我在我的React前端中有多个日期在一个数组中,格式为'MM/YYYY'。现在我想从MongoDB中获取我的历史记录,创建的时间范围为一个月。我如何在这个axios get请求中传递我的数据?
我的前端

let date = '11/2022'

    const getHistory = async () => {

      let monthYearStart = dayjs(date, 'MM/YYYY').format('YYYY.MM.01');
      let monthYearEnd = dayjs(date, 'MM/YYYY').format('YYYY.MM.32');

      const res = await axios.get('/api/monthlyhistory');
      setPdfHistory(res.data);
    };
    getHistory().then(() => {});

我的后端

try {
      const history = await History.find({
        status: true,
        createdAt: {
          $gte: dayjs(new Date(monthYearStart, 'YYYY.MM.DD')),
          $lt: dayjs(new Date(monthYearEnd, 'YYYY.MM.DD')),
        },
      });
      res.json(history);
    } catch (err) {
      return res.status(500).json({ msg: err.message });
    }
nwlqm0z1

nwlqm0z11#

一种选择是将日期作为查询参数传递。
客户端

// Note these are local dates
const monthYearStart = new Date(2022, 10); // month is a zero-based index
const monthYearEnd = new Date(monthYearStart);
monthYearEnd.setMonth(monthYearEnd.getMonth() + 1);
monthYearEnd.setDate(monthYearEnd.getDate() - 1);

const res = await axios.get("/api/monthlyhistory", {
  params: {
    monthYearStart: monthYearStart.toISOString(),
    monthYearEnd: monthYearEnd.toISOString(),
  },
});

服务器端

const { monthYearStart, monthYearEnd } = req.query;
const history = await History.find({
  status: true,
  createdAt: {
    $gte: new Date(monthYearStart),
    $lt: new Date(monthYearEnd),
  },
});

相关问题