-
Is there a way to know if we are inside a transaction when transactionAsyncLocalStorage is enabled? My use case is that I have three services, A, B and C, where A calls B, and B calls C. But I want to make sure that when B gets called directly (or not from A), it will use a transaction for itself, and service C. Simplified example: const AModel = mongoose.model('A', aSchema)
const BModel = mongoose.model('B', bSchema)
const CModel = mongoose.model('C', cSchema)
async function runA() {
return await mongoose.connection.transaction(async () => {
const a = await AModel.create({})
await runB(a)
return a
})
}
async function runB(a) {
// Here it would be great to know if we are in a transaction, so that
// I could start one if not already in a transaction
const b = await BModel.create({})
await runC(b)
return b
}
async function runC(b) {
const c = await CModel.create({})
return c
} |
Beta Was this translation helpful? Give feedback.
Answered by
vkarpov15
Sep 29, 2025
Replies: 1 comment 4 replies
-
Your best bet would be to access the transactionAsyncLocalStorage directly: const transactionAsyncLocalStorage = mongoose.transactionAsyncLocalStorage.getStore();
if (transactionAsyncLocalStorage.session && transactionAsyncLocalStorage.session.inTransaction()) {
// In transaction
} else {
// not in transaction
} Does that work for you? |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
mjanos10
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your best bet would be to access the transactionAsyncLocalStorage directly:
Does that work for you?