【问题标题】:MongoError: Cannot use a session that has ended (only on 1 collection)MongoError:无法使用已结束的会话(仅在 1 个集合上)
【发布时间】:2020-02-21 11:27:11
【问题描述】:

我正在运行 mongodb 4.2、expressjs 4.15 和节点 12.13。

在我的 api 运行时,我对 mongo 配置进行了一些更改。从那时起,我在尝试查询特定集合时遇到以下错误:

MongoError: Cannot use a session that has ended
at applySession (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/sessions.js:697:12)
at _command (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/wireprotocol/command.js:58:17)
at command (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/wireprotocol/command.js:28:5)
at Object.query (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/wireprotocol/query.js:57:3)
at Connection.query (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/cmap/connection.js:166:8)
at /Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/sdam/server.js:316:12
at Object.callback (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/cmap/connection_pool.js:347:7)
at /Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/cmap/connection_pool.js:497:23
at /Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/cmap/connection_pool.js:427:7
at callback (/Users/kendallyoder/Documents/api-three/node_modules/mongodb/lib/core/connection/connect.js:97:5)

这只发生在一个集合上,所有其他集合都可以提供数据。

我假设有一个会话挂在我需要清除的地方。我已经杀死并重新启动了我所有的开发进程,更新了 npm,重新安装了 mongodb,并清除了配置数据库中的所有“system.sessions”。

有什么想法吗?

mongo代码:

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, client) {
// console.log("mongo is awake")
// console.dir(MongoClient,{depth:null})

if(err) callback(null, err)
if(client) {
  const db = client.db(dbName)

  if(action == 'find') {
    db.collection(collection).find(query).project(project).sort(sort).limit(limit).toArray().then((records, err) => {
      if(err) callback(null, err)
      if(records) callback(records, null)
    })
  }

  // other "actions"

  client.close()
} 
})

【问题讨论】:

  • 我假设你看过stackoverflow.com/q/59816298/2367848,但由于这个问题是最近才出现的,也许它是相关的?我们可以拥有触发错误的代码吗?有什么配置变化?
  • 你说“尝试查询时”,但堆栈跟踪说“连接”,你能再提供一些代码吗?
  • @AntoineBolvy 是的,我看到了那个,但它不是很相关......我的代码很好,我可以完美地查询其他集合......它只是这个错误的集合。
  • 您可以直接编辑您的问题而不是在 cmets 中添加代码吗? + 之后从您的评论中删除代码:)

标签: node.js mongodb express session


【解决方案1】:

在回调中关闭连接

if(action == 'find') {
    db.collection(collection).find(query).project(project).sort(sort).limit(limit).toArray().then((records, err) => {
        if(err) callback(null, err)
            if(records) callback(records, null)
                client.close() <=============== Close here

    })
}

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多