Skip to content

Using a cusor/async loop loses the mongoose session #15949

@mjfwalsh

Description

@mjfwalsh

Prerequisites

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

Mongoose version

9.1.2 (and current HEAD 898399b)

Node.js version

25.2.1

MongoDB server version

8.2.3

Typescript version (if applicable)

No response

Description

Session is not attached to documents when using cursor / async loop.

Steps to Reproduce

#!/usr/bin/env node

import mongoose from 'mongoose';

const connection = mongoose.createConnection('mongodb://localhost:27017/quicktest');

const schema = new mongoose.Schema(
  {
    name: String,
    age: Number,
  },
  { strict: false }
);

// test data
const model = connection.model('Users', schema);

await model.create({ name: 'John', age: 5 });
await model.create({ name: 'Mark', age: 2 });
await model.create({ name: 'Mary', age: 7 });

// start transaction
const session = await connection.startSession();
session.startTransaction();

// query with session
const query = model.find({}).session(session);

// use async loop
for await (const person of query) {
  person.age += 10;
  
  // prints "true"
  console.log(person.$session() === null);
  await person.save();
}

// this should revert the changes
await session.abortTransaction();

// but it doesn't
const query2 = model.find({});
for await (const person of query2) {
  console.log(person.name, person.age);
}

await connection.db.dropDatabase();

process.exit(0);

Expected Behavior

Session should be attached to each document and aborting the transaction should revert the changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions