Model.create in a transaction
See original GitHub issueWith the recent introduction of transactions, various methods now accept an additional session
option. Unfortunately it made things a bit tricky for Model.create
.

Model.create
accepts options only if given an array. This means that a simple statement like this:
const instance = await SomeModel.create({
prop1: true,
prop2: 123
});
now becomes:
const instance = (await SomeModel.create([{
prop1: true,
prop2: 123
}], {session: ...}))[0];
It’s becoming hard to read, so it would be awesome if there would be a way to create a single document without having to pass an array.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7
Top Results From Across the Web
CreateTransactionModel | AvaTax API | Avalara Developer
Specifies the type of document to create. A document type ending with Invoice is a permanent transaction that will be recorded in AvaTax....
Read more >Mongoose v6.8.1: Transactions
To create a transaction, you first need to create a session using or Mongoose#startSession or Connection#startSession() . // Using Mongoose's default connection ...
Read more >The transactional model - IBM
The transactional model describes the way in which you can use transactions in message flows to accomplish certain tasks and results.
Read more >Add transaction to sequelize create module - Stack Overflow
The sequelize instance needs to be imported to use transactions. It is already exported in your database configuration file with this line ...
Read more >Transactions | Objection.js
# Creating a transaction ... In objection, a transaction can be started by calling the Model.transaction function: try { const returnValue = await...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@mushfau that’s because the create method accepts either an array of docs, or 1-n docs as a spread. Mongoose can’t differentiate between your options object and an intended doc. It thinks your options object is yet another document you want to insert, but since no properties match you schema, the only thing inserted is the _id.
The docs actually mention this:
@c-eliasson the ‘cannot create namespace’ error is a pretty common pain point when testing with transactions. You can use
Model.createCollection()
or theautoCreate
option to work around this.And re:
SomeModel(obj).save(session)
, that was a typo that I fixed. It should beSomeModel(obj).save({ session })
, see docs. Sorry about the confusion.