Skip to content

Commit

Permalink
Update MongoDB docs about directConnection
Browse files Browse the repository at this point in the history
  • Loading branch information
BradLewis authored Aug 22, 2024
1 parent 698241a commit 6e1213b
Showing 1 changed file with 32 additions and 11 deletions.
43 changes: 32 additions & 11 deletions packages/modules/mongodb/src/mongodb-container.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MongoDBContainer, StartedMongoDBContainer } from "./mongodb-container";
import { MongoDBContainer } from "./mongodb-container";
import mongoose from "mongoose";

describe("MongodbContainer", () => {
Expand All @@ -8,7 +8,26 @@ describe("MongodbContainer", () => {
it("should work using default version 4.0.1", async () => {
const mongodbContainer = await new MongoDBContainer().start();

await checkMongo(mongodbContainer);
// directConnection: true is required as the testcontainer is created as a MongoDB Replica Set.
const db = mongoose.createConnection(mongodbContainer.getConnectionString(), { directConnection: true });

// You can also add the default connection flag as a query parameter
// const connectionString = `${mongodbContainer.getConnectionString()}?directConnection=true`;
// const db = mongoose.createConnection(connectionString);

const fooCollection = db.collection("foo");
const obj = { value: 1 };

const session = await db.startSession();
await session.withTransaction(async () => {
await fooCollection.insertOne(obj);
});

expect(
await fooCollection.findOne({
value: 1,
}),
).toEqual(obj);

await mongoose.disconnect();
await mongodbContainer.stop();
Expand All @@ -19,15 +38,13 @@ describe("MongodbContainer", () => {
it("should work using version 6.0.1", async () => {
const mongodbContainer = await new MongoDBContainer("mongo:6.0.1").start();

await checkMongo(mongodbContainer);
// directConnection: true is required as the testcontainer is created as a MongoDB Replica Set.
const db = mongoose.createConnection(mongodbContainer.getConnectionString(), { directConnection: true });

await mongoose.disconnect();
await mongodbContainer.stop();
});
// }
// You can also add the default connection flag as a query parameter
// const connectionString = `${mongodbContainer.getConnectionString()}?directConnection=true`;
// const db = mongoose.createConnection(connectionString);

async function checkMongo(mongodbContainer: StartedMongoDBContainer) {
const db = mongoose.createConnection(mongodbContainer.getConnectionString(), { directConnection: true });
const fooCollection = db.collection("foo");
const obj = { value: 1 };

Expand All @@ -39,7 +56,11 @@ describe("MongodbContainer", () => {
expect(
await fooCollection.findOne({
value: 1,
})
}),
).toEqual(obj);
}

await mongoose.disconnect();
await mongodbContainer.stop();
});
// }
});

0 comments on commit 6e1213b

Please sign in to comment.