MongoDB集合文档提前过期:Mongoose过期时间设置异常
Mongoose邮箱验证文档提前过期的解决方案
问题根源
你的代码中createdAt字段的default设置存在错误:使用了Date.now()(带括号),这会在服务器启动时立即执行,将这个固定时间作为所有新文档的默认创建时间。比如服务器运行1小时后创建新文档,createdAt还是1小时前的时间,刚存入就满足过期条件,导致文档提前消失。
修复代码
把Date.now()改成Date.now(不带括号,传递函数引用,Mongoose会在创建每个文档时调用它获取实时时间):
const mongoose = require('mongoose'); const { Schema } = mongoose; const tokenSchema = new Schema({ userId: { type: Schema.Types.ObjectId, required: true, ref: 'user', unique: true }, token: { type: String, required: true }, createdAt: { type: Date, default: Date.now, // 去掉括号,传递函数引用 expires: 3600 } }); exports.EmailVerifyToken = mongoose.model('EmailVerifyToken', tokenSchema);
补充说明
Mongoose的expires选项是基于字段存储的时间加上指定秒数来计算过期时间的,因此必须保证createdAt的值是文档实际创建的时间,而非固定的服务器启动时间。
内容的提问来源于stack exchange,提问作者Pradeep
相关产品推荐
相关产品推荐

