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

「 The 'expireAfterSeconds' option is supported on '_ts' field only. 」 error is showed

我在 node.js 中使用 cosmos db 作为会话存储。而 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,
})

因此,显示以下消息。

  (node:16068) UnhandledPromiseRejectionWarning: MongoError: The 'expireAfterSeconds' option is supported on '_ts' field only.

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

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

Cosmos 目前仅支持 Cosmos 上的 TTL 索引 internal modification timestamp field _ts:

_ts is a Cosmos DB-specific field and is not accessible from MongoDB clients. It is a reserved (system) property that contains the timestamp of the document's last modification.

由于 connect-mongo 使用名为 expires 的字段作为 ttl 值,默认情况下它不适用于 Cosmos。

但是,您可以通过使用 connect-mongocompatibility mode 解决此问题,它在您的 Node 应用程序中使用效率较低的基于计时器的方法,而不是 [=30= 支持的本机 TTL 索引] 服务器:

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

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

为了在架构上创建集合级别的 ttl,请使用:

    schema.index({ _ts: 1 }, { expireAfterSeconds: 60 });