【问题标题】:「 The 'expireAfterSeconds' option is supported on '_ts' field only. 」 error is showed「 'expireAfterSeconds' 选项仅在 '_ts' 字段上受支持。 》 错误显示
【发布时间】:2020-01-08 02:45:03
【问题描述】:

我在 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.

这个问题有什么解决办法?

【问题讨论】:

  • 可能是因为你使用的是mongoose,它只支持MongoDB。 CosmosDB 是 Microsoft 产品,因此不受支持。
  • 我使用 mongoose.mongoose 可以与 CosmosDB 一起使用。因为 CosmosDB 兼容 mongoApi。

标签: node.js azure-cosmosdb azure-cosmosdb-mongoapi


【解决方案1】:

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

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

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

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

但是,您可以通过使用 connect-mongocompatibility mode 来解决此问题,它在 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)
})

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

【讨论】:

  • 感谢您的回复。我了解 Cosmos DB 的 TTL 索引。你教的这段代码工作正常。非常感谢!
【解决方案2】:

要在模式上创建集合级别 ttl,请使用:

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

【讨论】:

  • 如何设置_ts字段?或者它的价值是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 2021-12-21
相关资源
最近更新 更多