Mongoose聚合查询中日期$lt运算符使用返回空结果问题
问题解决思路
核心问题原因
你在$match阶段的日期条件里用了聚合操作符$toDate,但$match的查询条件属于MongoDB查询语法,并非聚合表达式上下文,这里不能直接使用$toDate这类聚合操作符。哪怕传入的是标准ISO日期字符串,用$toDate包裹后,MongoDB无法正确识别为Date类型做比较,导致条件不匹配,返回空结果。
修复方案
直接把日期字符串转换为JavaScript的Date对象传入,不用在聚合管道里用$toDate处理:
// 先将cursor字符串转为Date对象 const cursorDate = pageProps?.cursor ? new Date(pageProps.cursor) : new Date(); PostModel.aggregate([{ "$match": { "organisationId": "wHQcDpJaFqpRmeS7chXlh", // 直接用Date对象进行比较,无需$toDate "createdAt": { "$lt": cursorDate } } }, { "$lookup": { "from": "boards", "localField": "boardId", "foreignField": "_id", "as": "board" } }, { "$sort": { "createdAt": -1 } }, { "$limit": 10 } ]);
额外优化点
$match里的$and可以省略,MongoDB默认会把多个条件视为逻辑与关系,代码更简洁。- 转换Date对象时可以加合法性判断,避免无效日期导致的错误:
const cursorDate = pageProps?.cursor ? new Date(pageProps.cursor) : new Date(); if (isNaN(cursorDate.getTime())) { // 处理无效日期,比如设为当前时间 cursorDate = new Date(); }
内容的提问来源于stack exchange,提问作者Ali Celebi
相关产品推荐
相关产品推荐

