Search code examples
node.jsazure-cosmosdbazure-cosmosdb-mongoapi

「 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?


Solution

  • 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.