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: truenecessary when usingcreate()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!