'Transactions not working with mongoose but they do with MongoClient
I'm having some trouble with transactions, specifically while using mongoose.
I already have my replica set running with docker, to which I can connect without a problem, and if I try to use transactions with the mongoclient (official driver for node) it works like a charm, for example this is working
app.get('/users', async (_req, res) => {
const session = client.startSession();
session.startTransaction();
await client.db('db_auth').collection('users').insertOne(
{
name: 'John Doe',
email: '[email protected],',
},
{ session: session }
);
//await session.commitTransaction();
await session.abortTransaction().then((data) => {
console.log('transaction aborted', data);
});
session.endSession();
return client
.db('db_auth')
.collection('users')
.find({})
.toArray()
.then((data) => {
return res.json(data);
})
.catch((err) => {
console.error(err);
res.status(500).json('');
});
});
In this example the user is not added, I get the same result if instead of sesion.abortTransaction() I simply don't call session.commitTransaction()
But when trying to use transactions with mongoose (I tried version 6.3.0 and also 6.2.8), it just does not work.
app.get('/users', async (_req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
await new UserSchema(
{
name: 'John Doe',
email: '[email protected],',
},
{ session: session }
).save();
await session.abortTransaction().then(() => {
console.log('transaction aborted');
});
session.endSession();
return res.json(await UserSchema.find());
});
Even though I specifically aborted the transacation, or if I dont call session.commitTransaction(), the data gets added anyways.
I'm just not understanding if I'm doing something wrong or it has something to do with mongoose library, but help would be gladly accepted!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
