6

I use cosmos db for sesseion store in node.js. And cosmos db version is 3.6 .

I execute follwing code.

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

As result,following message is shown.

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

What is solution for this problem?

Stennie
  • 63,885
  • 14
  • 149
  • 175

3 Answers3

14

CosmosDB is a different server implementation from MongoDB and some features and behaviour differ.

Cosmos currently only supports TTL indexes on Cosmos' 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.

Since connect-mongo is using a field called expires for the ttl value, it will not work with Cosmos by default.

However, you can workaround this by using connect-mongo's compatibility mode which uses a less efficient timer-based approach in your Node application instead of the native TTL index supported by MongoDB servers:

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

You can adjust the timer interval with the autoRemoveInterval option which sets how often a query is run to remove expired documents.

Stennie
  • 63,885
  • 14
  • 149
  • 175
1

In order to create a collection level ttl on a schema, use:

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

Since MS Build 2023 the Cosmos Mongo API supports

TTL on absolute path (API for MongoDB): Now in GA, this feature gives Azure Cosmos DB for MongoDB the ability to create a time to live index on any date field, giving users more flexibility in determining when their documents will expire.

So you are no longer restricted to having to create it on the _ts field.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845