mongoose-transactions icon indicating copy to clipboard operation
mongoose-transactions copied to clipboard

Support mongoose.createConnection

Open ethanwillis opened this issue 6 years ago • 4 comments

See the following SO post for context.

https://stackoverflow.com/questions/22786374/queries-hang-when-using-mongoose-createconnection-vs-mongoose-connect

Essentially for downstream projects, like mine, that use mongoose.createConnection instead of mongoose.connect.. we use all db.model instead of mongoose.model. Currently this package assumes mongoose.model will work in all instances, however it does not.

ethanwillis avatar Jul 01 '18 00:07 ethanwillis

I agree. I'm using createConnection too. Please, consider it.

emauriciomoreno avatar Feb 05 '19 20:02 emauriciomoreno

Hi guys, thanks for the informations.

I need to study this use case and to add a solution in our roadmap.

daton89 avatar Feb 05 '19 21:02 daton89

Hi guys, thanks for the informations.

I need to study this use case and to add a solution in our roadmap.

I am currently creating an application that runs in aws lambda, I use createConnection to store cached DBS so that the lambda can connection to different DBs based on who send a request to it.

been trying to get this working this afternoon to find this issue :(

vorticalbox avatar Sep 23 '19 15:09 vorticalbox

been playing about and finally have a working transaction using mongoose directly, so until this package is updated you can use the following.

const mongoose = require('mongoose');
const uri = 'YOUR CONNECTION STRING HERE';
const  conn = await mongoose.createConnection(uri, { promiseLibrary: Promise, useNewUrlParser: true});
const testModel = conn.model('test', new mongoose.Schema({name: String}));
const session = await conn.startSession();
session.startTransaction();

try {
    await testModel.create([{ name: 'test'}], {session})
    await session.commitTransaction();
    session.endSession();
} catch (error) {
    session.abortTransaction();
}

some notes:

transactions require a replica set and must support retryable writes and an engine that supports document level locking such as wiredTiger.

You must create all your collections before trying to save as

Operations that affect the database catalog, such as creating or 
dropping a collection or an index, are not allowed 
in multi-document transactions.  
For example, a multi-document transaction cannot include an
insert operation that would result in the creation of a 
new collection. See Restricted Operations.

https://docs.mongodb.com/manual/core/transactions/

vorticalbox avatar Sep 24 '19 10:09 vorticalbox