MongoDB查询指定字段并转换时间戳为日期时报错排查
问题原因及解决方案
错误原因
- find方法参数顺序错误:
Answer.find()的第三个参数应为配置选项对象(如limit、sort这类),你传入的字段列表字符串被系统识别为options参数,但它不是对象,因此触发Options must be an object错误。 - 聚合操作符使用场景错误:
$toDate是MongoDB聚合框架的专属操作符,不能直接在find的投影参数中使用,find的投影仅支持指定字段显隐或简单字段映射。
修复方案
方案1:使用聚合管道(数据库层面转换日期)
用aggregate替代find,先通过$match筛选目标数据,再用$project完成日期转换并指定返回字段:
const answers = await Answer.aggregate([ { $match: { userId: req.params.userId } }, { $project: { _id: 1, formId: 1, title: 1, username: 1, date: 1, createdAt: { $toDate: "$createdAt" } } } ]);
方案2:查询后在应用层转换日期
如果坚持使用find,先获取原始数据,再通过代码将时间戳转为日期对象:
const answers = await Answer.find( { userId: req.params.userId }, "_id formId title username date createdAt" ); // 遍历转换createdAt字段 answers.forEach(item => { item.createdAt = new Date(item.createdAt); });
内容的提问来源于stack exchange,提问作者JS24
相关产品推荐
相关产品推荐

