2

I’m using [email protected] with [email protected]. 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:

  • Why is ordered: true necessary when using create() with session and multiple documents?
  • Is this the recommended approach or is there a better way to bulk insert with session support?
  • Will this affect performance or the way errors are handled in bulk inserts?

Any insights or official documentation links would be appreciated!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.