skip to Main Content

i am trying to get a string from all documents in a mongo db collection, but when it starts it give me an error:

106 |      * not subject to semantic versioning compatibility guarantees and may change at any time.
107 |      *
108 |      * @public
109 |      **/
110 |     constructor(message, options) {
111 |         super(message, options);
              ^
error: Cannot use a session that has ended
      at new MongoError (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodbliberror.js:111:9)
      at new MongoDriverError (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodbliberror.js:209:9)
      at new MongoAPIError (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodbliberror.js:238:9)
      at new MongoExpiredSessionError (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodbliberror.js:403:9)
      at applySession (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibsessions.js:708:16)
      at prepareCommand (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibcmapconnection.js:169:49)
      at C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibcmapconnection.js:259:30
      at C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibcmapconnection.js:313:26
      at command (C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibcmapconnection.js:311:23)
      at C:UsersUtenteDesktopSkyForce Helpernode_modulesmongodblibsdamserver.js:167:40

my function:

export async function returnAllRep(): Promise<string[]> {
    const { client, database } = await connectToDatabase();
    const collection = database.collection('chains'); 
    
    try {
        const docs = await collection.find().toArray();
        
        const ids = docs.map(doc => doc.id);
        
        return ids;
    } catch (error) {
        console.error('Errore durante la recuperazione dei documenti:', error);
        throw error;
    } finally {
        await client.close();
    }
}

I have trying to add debug when it connect to the db, it says it’s connected but then it crash

If i try with a single document it works, but i need all the document

2

Answers


  1. To connect your client to the MongoDB cluster, and retrieve your database, I would use the following syntax instead.

    import { MongoClient } from "mongodb";
    
    // Define your connection string and database
    const MONGODB_URI = "<connection string>";
    const DATABASE = "<database name>";
    
    // Connect to the client and get your collection object
    const client = await MongoClient.connect(MONGODB_URI);
    const collection = client.db(DATABASE).collection("chains");
    
    const docs = await collection.find().toArray();
    

    It seems like the way you are getting the database is different.

    Login or Signup to reply.
  2. The error you are encountering, "Cannot use a session that has ended,", typically happens when you are trying to use a MongoDB session that has already been closed or expired. This can occur due to the session timing out or if you manually ended the session and then attempted to use it again.

    To resolve this, you need to ensure that you do not reuse a session after it has been ended. Here’s a basic example of how to correctly use a session with MongoDB, making sure it is properly created, used, and ended after the operations.

    Below is an example of how to get strings from all documents in a MongoDB collection:

    1. Connection Setup:
      A function to retrieve documents from the collection, keeping session handling in mind.

      const { MongoClient } = require('mongodb');
      
      async function run() {
          const uri = 'your-mongodb-uri';
          const client = new MongoClient(uri);
          let session;
      
          try {
              // Connect to the MongoDB cluster
              await client.connect();
      
              // Create a session
              session = client.startSession();
      
              // Define the database and collection
              const database = client.db('your-database');
              const collection = database.collection('your-collection');
      
              // Start a session and perform operations
              session.startTransaction();
              const documents = await collection.find({}).toArray();
              session.commitTransaction();
      
              // Process your documents
              documents.forEach(doc => {
                  console.log(doc.yourField); // Replace 'yourField' with the actual field you want
              });
          } catch (error) {
              if (session) {
                  await session.abortTransaction();
              }
              console.error('Error: ', error);
          } finally {
              if (session) {
                  session.endSession();
              }
              await client.close();
          }
      }
      
      run().catch(console.error);
      

    Key Points:

    1. startSession: We explicitly start a new session.
    2. Transaction: We start a transaction (though not strictly required for a simple read operation, it showcases session management).
    3. commitTransaction: Commits the run if everything goes well.
    4. endSession: Properly ends the session by either committing or aborting the transaction based on the operation’s success.
    5. Exception Handling: Ensures that in the event of an error, appropriate cleanup is done by ending the session and closing the client connection.

    Make sure you replace 'your-mongodb-uri', 'your-database', 'your-collection', and 'yourField' with actual values from your MongoDB setup.

    Additional Tips:

    • Avoid reusing the same session for multiple distinct operations to prevent scenarios where a session may time out or be misused.
    • Check your MongoDB server settings: Ensure that any settings related to session timeouts or maximum session duration are appropriate for your use case.

    If you handle sessions carefully and ensure they’re properly managed and closed, you should be able to avoid the MongoExpiredSessionError.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search