Mongoose Schema设置createdAt默认值为new Date()仅返回服务器启动时间问题
问题原因解释
核心原因
你在Schema中配置的default: new Date()属于立即执行表达式,会在代码首次加载运行(也就是服务启动、Schema初始化)的阶段就计算出一个固定的时间值,后续所有未手动传入createdAt字段的新记录,都会复用这个提前生成的固定时间戳,所以所有记录的创建时间都和服务启动时间一致。
更优的原生解决方案
你不需要手动在业务逻辑中生成时间传入,只需要把Schema的默认值配置改为函数形式即可:
const itemSchema = mongoose.Schema({ person_name: String, person_position: String, person_level: String, createdAt: { type: Date, default: () => new Date(), // 改为函数形式,每次需要生成默认值时才会执行计算当前时间 }, });
Mongoose规则中,如果字段默认值配置为函数,会在每次创建新实例需要生成默认值的时候主动调用该函数,取返回值作为对应字段的默认值,这样就能保证每次拿到的都是记录创建的实时时间。
除此之外,Mongoose内置了自动维护时间戳的能力,你甚至不需要手动定义createdAt字段,直接在Schema配置中开启timestamps即可,它会自动帮你维护createdAt(记录创建时间)和updatedAt(记录更新时间)两个字段:
const itemSchema = mongoose.Schema({ person_name: String, person_position: String, person_level: String, }, { timestamps: true });
内容的提问来源于stack exchange,提问作者kartal şahin
相关产品推荐
相关产品推荐

