You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoDB和Mongoose遇TypeError: Session.createIndex is not a function求助

解决Mongoose自动删除过期文档的报错问题

问题原因

  1. Mongoose的Model实例没有createIndex方法,需通过Schema来定义索引规则。
  2. MongoDB的TTL索引必须关联日期类型字段,无法直接对非日期字段设置过期逻辑。

修改后的代码示例

方式一:在Schema字段中直接配置过期时间

这是最简洁的实现方式,直接在日期字段上设置expires参数:

const mongoose = require('mongoose');

// 定义Schema结构
const sessionSchema = new mongoose.Schema({
  key: String,
  // 添加自动过期的日期字段,默认值为当前时间
  createdAt: {
    type: Date,
    default: Date.now,
    expires: 60 * 60 * 15 // 过期时间:15小时,单位为秒
  }
});

// 创建Model
const Session = mongoose.model('session', sessionSchema);

方式二:通过Schema的index方法创建TTL索引

如果需要单独管理索引规则,可使用这种方式:

const mongoose = require('mongoose');

const sessionSchema = new mongoose.Schema({
  key: String,
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// 为createdAt字段创建TTL索引,指定15小时后过期
sessionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 60 * 60 * 15 });

const Session = mongoose.model('session', sessionSchema);

补充说明

  • 插入文档时,若未手动赋值createdAt,会自动使用当前时间作为默认值。
  • MongoDB的TTL后台进程约每60秒扫描一次集合,所以过期文档的删除可能存在一定延迟。

内容的提问来源于stack exchange,提问作者c321321sda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 00:55:17