如何在Prisma Schema中为MongoDB配置TTL过期索引?
在Prisma 4.14.0中通过Schema配置MongoDB TTL索引的问题
Prisma 4.14.0版本不支持直接在prisma.schema中定义MongoDB的TTL(自动过期)索引,目前只能通过原生命令或迁移脚本的方式实现,以下是详细说明:
为什么Schema里无法配置?
Prisma对MongoDB的索引支持在4.14.0版本中仅覆盖基础的单键、复合索引,对于需要指定expireAfterSeconds这类特殊参数的TTL索引,Schema的DSL语法没有提供对应的配置项,无法直接通过@index注解实现。
可行的替代方案
1. 使用$runCommandRaw创建索引
这就是你已经在使用的方式,可以将索引创建逻辑放在应用启动阶段,确保服务启动时索引已存在:
await prisma.$runCommandRaw({ createIndexes: 'UserActivity', indexes: [ { key: { createdAt: 1 }, name: 'createdAt_ttl_index', expireAfterSeconds: 120, // 对应2分钟 }, ], });
2. 通过Prisma迁移脚本创建索引
你可以在Prisma迁移中添加自定义脚本,确保索引在迁移时被创建(同时支持回滚):
- 生成一个空迁移:
npx prisma migrate dev --name add_ttl_index - 打开生成的迁移目录下的
migration.js文件,替换内容为:
module.exports = { async up() { await this.db.runCommand({ createIndexes: 'UserActivity', indexes: [ { key: { createdAt: 1 }, name: 'createdAt_ttl_index', expireAfterSeconds: 120, }, ], }); }, async down() { await this.db.runCommand({ dropIndexes: 'UserActivity', index: 'createdAt_ttl_index', }); }, };
- 执行迁移:
npx prisma migrate dev
后续版本的可能性
如果后续升级Prisma,官方可能会扩展@index注解的参数,支持直接在Schema中配置TTL索引,但4.14.0版本暂不支持此功能。
内容的提问来源于stack exchange,提问作者Fatema Tuz Zuhora
相关产品推荐
相关产品推荐

