node.jsmongodbmongoosebackend

Mongodb & mongoose :: Cannot call create() with a session and multiple documents unless ordered: true is set


I’m using mongoose@8.13.2 with mongodb@6.15.0. I’m trying to use the create() method in Mongoose along with a session for transaction support. However, when I try to insert multiple documents, I get the following error:

“Cannot call create() with a session and multiple documents unless ordered: true is set”

Here is the relevant part of my code:

async create(
  payload: Array<Partial<OrderDocument>>,
  options?: CreateOptions,
) {
  try {
    return this.orderModel.create(payload, { ...options, ordered: true });
  } catch (error) {
    throw error;
  }
}

Here's how I use it:

const create = await this.ordersDBController.create([],{ session });

Context:

I’m passing an array of documents in payload. I use a session in options for transactions (i.e., options = { session }). The error seems to happen only when using both a session and multiple documents.

What I’ve tried:

Adding { ordered: true } to the options, as the error message suggests, seems to solve the problem. But I’m wondering why this is required only when a session is present. Is this a new behavior in Mongoose 8 or MongoDB 6?

Questions:

Any insights or official documentation links would be appreciated!


Solution

  • That error was added in this commit

    The commit message includes Fix #15091

    In Issue 15091 the reporter was seeing errors like

    Given transaction number 1 does not match any in-progress transactions. The active transaction number is -1
    

    when calling create with a session and an array of documents.

    The issue discussion includes the following explanation:

    MongoDB does not allow multiple operations in the same transaction in parallel, so create() on multiple docs with a session option may fail because create() saves multiple documents in parallel by default.

    You can either use insertMany(), or use the ordered option for create()

    As noted in the docs, when calling create with a session, the documents are created within a transaction.