从Mongoose迁移Prisma:密码隐藏及过期字段设置求助
2. 创建VerificationToken模型并自动生成过期时间
方法1:数据库层面设置默认值(分数据库)
根据你使用的数据库,在Prisma Schema中配置expiresAt的默认值:
PostgreSQL
model VerificationToken { id String @id @default(cuid()) token String @unique userId String expiresAt DateTime @default(dbgenerated("NOW() + INTERVAL '10 minutes'")) user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@index([userId]) }
MySQL
model VerificationToken { id String @id @default(cuid()) token String @unique userId String expiresAt DateTime @default(dbgenerated("DATE_ADD(NOW(), INTERVAL 10 MINUTE)")) user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@index([userId]) }
方法2:代码层面计算(跨数据库通用)
创建记录时手动计算10分钟后的时间,适配所有数据库:
// 引入crypto生成唯一token(Node.js环境) import crypto from 'node:crypto'; const createVerificationToken = async (userId) => { return await prisma.verificationToken.create({ data: { token: crypto.randomUUID(), userId, expiresAt: new Date(Date.now() + 10 * 60 * 1000), // 当前时间加10分钟 }, }); };
内容的提问来源于stack exchange,提问作者Ayush Kathariya
相关产品推荐
相关产品推荐

