【问题标题】:Error setting TTL index on collection : sessions (MongoDB/MongoHQ)在集合上设置 TTL 索引时出错:会话 (MongoDB/MongoHQ)
【发布时间】:2024-05-01 18:15:04
【问题描述】:

我能够连接到我的主数据库没有问题,但是当我尝试连接到我的副本集时,我得到了 TTL 错误。我已尽力包含所有相关的代码示例,但请询问您是否需要查看未包含的内容。这让我很生气。数据库位于 mongoHQ。

那么,问题来了:

  • 我可以连接到我的主集 (workingDB)
  • 我无法连接到我的副本集 (failingDB)
  • 尝试连接两者时无法连接 (mongoHQ)。

代码示例

mongoHQ = "mongodb://<user>:<password>@candidate
.14.mongolayer.com:10120/dbName,mongodb://<user>:<password>@candidate
.15.mongolayer.com:10120"

failingDB = "mongodb://<user>:<password>@candidate
.14.mongolayer.com:10120/dbName"

workingDB = "mongodb://<user>:<password>@candidate
.15.mongolayer.com:10120/dbName"


# DB Options
opts =
  mongos: true
  server:
    auto_reconnect: true

# Connect to DB
mongoose.connect mongoHQ, opts


# express/mongo session storage
app.use express.session(
  secret: "Secrets are for children"
  cookie:
    maxAge: process.env.SESSION_TTL * 3600000
    httpOnly: false
  store: new mongoStore(
    url: mongoHQ
    collection: "sessions"
  , ->
    console.log "We're connected to the session store"
    return
  )
)

# Error: Error setting TTL index on collection : sessions

# * Connecting to "workingDB" works as expected.
# * Connecting to "failingDB" throws the same TTL Error
# * candidate.14 is the primary set, candidate.15 is the replica set

【问题讨论】:

  • 您在 MongoStore 中使用了哪个模块?你得到这个工作了吗?谢谢
  • 嘿@JasonGelinas,我可以通过简单地删除 URI 中对副本集的引用来解决这个问题。请参阅下面的答案。
  • @JasonGelinas 和我在 mongoStore 中使用了 connect-mongo。

标签: node.js session coffeescript mongohq ttl


【解决方案1】:

也许有点晚了,但我今天在 MongoHQ 和 Mongoose 上遇到了类似的错误。我通过删除选项mongos: true 解决了它(至少目前,手指交叉)。我认为副本集并不真正需要该选项(仅在使用 mongos 服务器时):

http://mongoosejs.com/docs/connections.html#replicaset_connections

http://support.mongohq.com/languages/mongoose.html

另外,最好等待连接建立后再尝试设置 MongoStore,例如:

mongoose.connect(mongoHQ);
var db = mongoose.connection;

db.on('error', function () {
  // Panic
});

db.on('connected', function() {
    var app = express();
    app.use(express.session(sessionOptions));
    // etc...
    app.listen(config.port, function() {
        console.log('Listening on port ', config.port);
    });
});

【讨论】:

    【解决方案2】:

    我可以通过简单地删除 URI 中对副本集的引用来解决问题

    mongoHQ = "mongodb://<user>:<password>@candidate.15.mongolayer.com:10120/dbName";
    

    【讨论】: