如何在Express应用中使用Mongoose查询指定日期范围内的客户列表
实现方案
1. 后端Express路由改造
你已经在Schema中配置了timestamps: true,Mongoose会自动为每个客户文档生成createdAt(创建时间)和updatedAt(最后更新时间)两个Date类型字段,直接基于这两个字段做范围查询即可。
我们可以直接改造现有/list接口,兼容日期范围查询的同时不影响原有逻辑:
router.get('/list', (req, res) => { // 构造查询条件 const filter = {} const { startDate, endDate } = req.query // 传入起始日期则添加大于等于起始日期的筛选条件 if (startDate) { filter.createdAt = { ...filter.createdAt, $gte: new Date(startDate) } } // 传入结束日期则添加小于等于结束日期的筛选条件 if (endDate) { filter.createdAt = { ...filter.createdAt, $lte: new Date(endDate) } } Customer.find(filter) .then((cx) => { if (!cx) { res .status(400) .send('Error getting customer'); } else { res.send(cx); } }) .catch((err) => { res.status(500).json({ err }); }); });
2. 前端React请求示例
拿到日期选择器的起始、结束日期后,转成ISO格式字符串作为查询参数传递即可,以Axios请求为例:
// 示例用dayjs处理日期,start、end为日期选择器返回的日期对象 import axios from 'axios' import dayjs from 'dayjs' const getCustomerByDateRange = async (start, end) => { const params = {} if (start) params.startDate = dayjs(start).startOf('day').toISOString() // 取起始日期当天0点,避免漏掉当天早于当前时间的记录 if (end) params.endDate = dayjs(end).endOf('day').toISOString() // 取结束日期当天23:59:59,避免漏掉当天晚于当前时间的记录 const res = await axios.get('/api/customer/list', { params }) console.log('指定日期范围的客户数据:', res.data) }
补充说明
- 如果需要按客户最后更新时间筛选,把查询条件里的
createdAt替换为updatedAt即可 - 该实现兼容原有逻辑,不传日期参数时默认返回全部客户数据
- 建议前端统一传递ISO格式的日期字符串,避免时区差异导致的查询误差
内容的提问来源于stack exchange,提问作者Twisam Stark
相关产品推荐
相关产品推荐

