Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MongoExpiredSessionError: Cannot use a session that has ended when using Model.collection.find_.populate #15195

Open
2 tasks done
KhaledMosaad opened this issue Jan 22, 2025 · 1 comment
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.

Comments

@KhaledMosaad
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.9.x

Node.js version

22.x

MongoDB server version

7

Typescript version (if applicable)

No response

Description

When using Model.collection.findOne.populate(....) the Driver shutdown the session that running and end up with MongoExpiredSessionError: Cannot use a session that has ended
here's the full exception:

MongoExpiredSessionError: Cannot use a session that has ended

      at applySession (node_modules/mongodb/src/sessions.ts:1101:12)
      at Connection.prepareCommand (node_modules/mongodb/src/cmap/connection.ts:380:40)
      at Connection.sendCommand (node_modules/mongodb/src/cmap/connection.ts:498:26)
          at sendCommand.next (<anonymous>)
      at Connection.command (node_modules/mongodb/src/cmap/connection.ts:617:22)
      at Server.command (node_modules/mongodb/src/sdam/server.ts:337:32)
      at FindOperation.execute (node_modules/mongodb/src/operations/find.ts:130:12)
      at tryOperation (node_modules/mongodb/src/operations/execute_operation.ts:278:14)
      at executeOperation (node_modules/mongodb/src/operations/execute_operation.ts:112:12)
      at FindCursor._initialize (node_modules/mongodb/src/cursor/find_cursor.ts:90:22)
      at FindCursor.cursorInit (node_modules/mongodb/src/cursor/abstract_cursor.ts:896:21)
      at FindCursor.fetchBatch (node_modules/mongodb/src/cursor/abstract_cursor.ts:934:7)
      at FindCursor.next (node_modules/mongodb/src/cursor/abstract_cursor.ts:569:9)
      at Collection.findOne (node_modules/mongodb/src/collection.ts:524:17)

Don't know if it's possible to use .populate with .collection methods or not, but the error is not an obvious one and should be more clear

Steps to Reproduce

Say we have a collection named Schools and another one named Classes

  • Create school document with classIds inside it
await Schools.create({ name: 'example_name', classIds: [ObjectId('1'),ObjectId('3'),ObjectId('2')]});
  • Query the school collection and populate the classIds
const schools = Schools.collection.findOne({_id:someSchoolId}).populate('classIds');

the exception will occur

Expected Behavior

No response

@vkarpov15
Copy link
Collaborator

I'm unable to repro, the following script fails with the correct error message TypeError: School.collection.findOne(...).populate is not a function.

You're right that Schools.collection.findOne() returns a plain JavaScript promise, not a Mongoose query, so .collection.findOne().populate() results in a TypeError. Does your TypeScript compiler not catch this error?

const mongoose = require('mongoose');

// MongoDB connection
mongoose.connect(my connection string here);

// Define schemas and models
const ClassSchema = new mongoose.Schema({ name: String });
const Class = mongoose.model('Class', ClassSchema);

const SchoolSchema = new mongoose.Schema({
  name: String,
  classIds: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Class' }]
});
const School = mongoose.model('School', SchoolSchema);

(async () => {
  await Class.deleteMany({});
  await School.deleteMany({});

  await mongoose.connection.transaction(async (session) => {
    // Create some classes
    const class1 = await Class.create([{ name: 'Class 1' }], { session });
    const class2 = await Class.create([{ name: 'Class 2' }], { session });
    const class3 = await Class.create([{ name: 'Class 3' }], { session });

    // Create a school with references to the classes
    const school = await School.create([
      {
        name: 'Example School',
        classIds: [class1[0]._id, class2[0]._id, class3[0]._id]
      }
    ], { session });

    // Attempt to use `.populate()` on `collection.findOne()`
    const result = await School.collection.findOne({ _id: school[0]._id }, { session }).populate('classIds');
    console.log(result);
  });

  await mongoose.disconnect();
})();

@vkarpov15 vkarpov15 added the can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. label Feb 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.
Projects
None yet
Development

No branches or pull requests

2 participants