You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose嵌套对象日期范围查询返回空结果的问题排查

解决Mongoose中嵌套日期范围查询问题

你的问题出在嵌套字段的查询写法上,原查询用了{ votingPeriod: { "endDate": { $gte: new Date()}}}这种格式,这是MongoDB的精确对象匹配——它要求整个votingPeriod对象只有endDate这一个键且满足条件,但你的votingPeriod还包含startDate,所以永远匹配不到数据,自然返回空。

要实现“当前日期处于startDate和endDate之间”的查询,需要用点符号访问嵌套字段,同时设置两个条件:

  • 当前日期不晚于votingPeriod.startDate(用$lte)
  • 当前日期不早于votingPeriod.endDate(用$gte)

正确的查询代码如下:

const organizations = await this.organizationRepository.find({
  "votingPeriod.startDate": { $lte: new Date() },
  "votingPeriod.endDate": { $gte: new Date() }
});

另外不需要调用.toISOString(),new Date()会被Mongoose自动转换为MongoDB兼容的ISODate类型,直接使用即可。

内容的提问来源于stack exchange,提问作者Hamza J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:24:37