Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 915
Ryusuke Kawasaki Avatar asked Dec 14 '22 09:12

Ryusuke Kawasaki


2 Answers

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.

like image 154
Stennie Avatar answered Dec 21 '22 10:12

Stennie


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

    schema.index({ _ts: 1 }, { expireAfterSeconds: 60 });
like image 35
Emil Sunesson Avatar answered Dec 21 '22 11:12

Emil Sunesson