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

Mongoose查询子文档返回空数组问题求助

问题解决方法

1. 修正查询条件写法

你的查询语句存在错误,MongoDB查询嵌套子文档的字段需要使用点符号(dot notation)。原写法{ toDoEmail: {email:email} }会尝试匹配整个toDoEmail子文档完全等于{email:email}(忽略了子文档内的createdAt和updatedAt字段),因此无法命中目标数据。

修改控制器中的查询代码:

const toDos = await toDoModel.find({ "toDoEmail.email": email });

2. 修复模型日期字段的不合理定义(建议)

你模型中所有子文档的createdAt和updatedAt被定义为String类型,但默认值是new Date()(Date对象),这会导致存储时自动转成字符串,后续按日期筛选、排序会受限。建议改为Date类型:

// 示例:修改title schema,其他子文档schema同理调整
const title = new schema({
  title: {
    type: String,
    trim: true,
    required: [true, "Title is required to create a ToDo"],
  },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now },
});

另外你已经开启了顶层的timestamps: true,会自动生成全局的createdAt和updatedAt,如果子文档的日期字段不是必须的,可以考虑移除,避免冗余。

3. 验证参数与存储值的一致性

确认URL传入的邮箱和数据库中存储的邮箱完全一致(注意大小写、首尾空格、特殊字符),可以直接在数据库中查看对应文档的toDoEmail.email值,和控制台打印的请求参数对比。

内容的提问来源于stack exchange,提问作者TechLife Journal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:42:44