ken yoder
ken yoder

Reputation: 31

MongoError: Cannot use a session that has ended (only on 1 collection)

i am running mongodb 4.2, expressjs 4.15, and node 12.13.

while my api was running, i made some changes to mongo configuration. ever since then i have been getting the following error when trying to query a specific collection:

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)

this only happens on one collection, all the other collections will give data just fine.

im assuming there is a session hung somewhere that i need to clear. i have already killed and restarted all my dev processes, updated npm, reinstalled mongodb, and cleared all "system.sessions" in the config database.

any ideas?

mongo code:

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()
} 
})

Upvotes: 2

Views: 4606

Answers (1)

Close the connection inside the callback

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

    })
}

Upvotes: 5

Related Questions