? 'expireAfterSeconds' 选项仅在 '_ts' 字段上受支持。? 显示错误

Ryu*_*aki 3 node.js azure-cosmosdb azure-cosmosdb-mongoapi

我在 node.js 中使用 cosmos db 进行会话存储。宇宙数据库版本是 3.6 。

我执行以下代码。

const expressSession = require("express-session");
const MongoStore = require("connect-mongo")(expressSession);
const store = new MongoStore({
        mongooseConnection: mongoose.connection,
        ttl:24 * 60 * 60 * 1000,
})
Run Code Online (Sandbox Code Playgroud)

结果,显示以下消息。

  (node:16068) UnhandledPromiseRejectionWarning: MongoError: The 'expireAfterSeconds' option is supported on '_ts' field only.
Run Code Online (Sandbox Code Playgroud)

这个问题的解决方案是什么?

Ste*_*nie 10

CosmosDB 是与 MongoDB 不同的服务器实现,并且某些功能和行为有所不同。

Cosmos 目前仅支持 Cosmos内部修改时间戳字段_ts上的 TTL 索引:

_ts是 Cosmos DB 特定的字段,无法从 MongoDB 客户端访问。它是一个保留(系统)属性,包含文档上次修改的时间戳。

由于 connect-mongo使用的是调用expiresttl值的字段,因此默认情况下它不适用于 Cosmos。

但是,您可以通过使用connect-mongo兼容模式解决此问题,该 模式在 Node 应用程序中使用效率较低的基于计时器的方法,而不是 MongoDB 服务器支持的本机 TTL 索引:

const store = new MongoStore({
        mongooseConnection: mongoose.connection,
        ttl:24 * 60 * 60 * 1000,
        autoRemove: 'interval',
        autoRemoveInterval: 10 // Value in minutes (default is 10)
})
Run Code Online (Sandbox Code Playgroud)

您可以使用autoRemoveInterval设置查询运行频率以删除过期文档的选项来调整计时器间隔。