如何在Axios GET请求中传参筛选MongoDB指定月份的createdAt数据
解决方法
1. 前端:用Axios GET传递多日期参数
GET请求传数组参数直接用Axios的params配置即可,它会自动把数组序列化成dates=11/2022&dates=10/2022这种格式,后端能直接识别处理。
修改后的前端代码(假设你有一个多日期数组dateArray):
// 你的多日期数组示例 const dateArray = ['11/2022', '10/2022']; const getHistory = async () => { try { const res = await axios.get('/api/monthlyhistory', { params: { dates: dateArray } }); setPdfHistory(res.data); } catch (err) { console.error('获取历史数据失败:', err); } }; getHistory();
如果想在前端先处理每个月份的起止时间再传给后端,可以把每个日期的首尾时间转成ISO字符串,拼成数组后转成JSON字符串传递:
const dateRanges = dateArray.map(date => ({ start: dayjs(date, 'MM/YYYY').startOf('month').toISOString(), end: dayjs(date, 'MM/YYYY').endOf('month').toISOString() })); const res = await axios.get('/api/monthlyhistory', { params: { ranges: JSON.stringify(dateRanges) } });
2. 后端:接收参数并查询MongoDB
后端先拿到前端传的dates数组,为每个日期生成对应的月份时间范围,用MongoDB的$or条件查询createdAt落在任意指定月份内的数据。
另外你原代码的日期处理有错误,别用YYYY.MM.32这种写法,用startOf('month')和endOf('month')才能准确获取当月首尾时间。修改后的后端代码:
try { // 处理参数:如果是单个日期就转成数组,统一逻辑 const { dates } = req.query; const dateList = Array.isArray(dates) ? dates : [dates]; // 为每个日期生成MongoDB查询条件 const monthConditions = dateList.map(dateStr => { const monthStart = dayjs(dateStr, 'MM/YYYY').startOf('month').toDate(); const monthEnd = dayjs(dateStr, 'MM/YYYY').endOf('month').toDate(); return { createdAt: { $gte: monthStart, $lte: monthEnd } }; }); // 查询status为true,且createdAt在任意指定月份的数据 const history = await History.find({ status: true, $or: monthConditions }); res.json(history); } catch (err) { return res.status(500).json({ msg: err.message }); }
要注意的几个点
- 日期处理必须用
startOf('month')和endOf('month'),别手动写固定日期,否则遇到2月、30天的月份会出错 - 确保MongoDB中的
createdAt字段是Date类型,不是字符串,否则日期查询会失效 - Axios传数组参数时直接用
params: { dates: dateArray }即可,不用手动拼接URL,避免编码问题
内容的提问来源于stack exchange,提问作者zuzuzuu
相关产品推荐
相关产品推荐

