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

如何使用Mongoose查询今日过生日的用户

使用Mongoose v5查询今日过生日的用户

要找出今日过生日的用户,核心是忽略birthdate字段中的年份,只匹配月份和日期。结合MongoDB的聚合表达式,用Mongoose的find()就能实现这个需求,具体步骤如下:

1. 获取今日的月份和日期

注意MongoDB的$month返回值是1-12,而JavaScript原生getMonth()返回0-11,所以需要做加1转换:

const today = new Date();
const targetMonth = today.getMonth() + 1; // 转为1-12的格式
const targetDay = today.getDate();

2. 构造查询条件

使用$expr允许在查询中使用聚合运算符,提取birthdate的月份和日期后,与今日的对应值做对比:

const User = mongoose.model('User', userSchema);

async function fetchTodayBirthdayUsers() {
  const birthdayUsers = await User.find({
    $expr: {
      $and: [
        { $eq: [{ $month: '$birthdate' }, targetMonth] },
        { $eq: [{ $dayOfMonth: '$birthdate' }, targetDay] }
      ]
    }
  });
  return birthdayUsers;
}

重要提示

  • 不要直接用birthdate: new Date()做匹配,这只会找到当年出生且今日生日的用户,完全不符合需求。
  • 如果应用涉及跨时区场景,需要先对birthdate和当前日期做统一时区转换后再匹配,避免时差导致的查询误差。

内容的提问来源于stack exchange,提问作者Hector Toro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:06:36