Skip to content

Commit 6e1213b

Browse files
authored
Update MongoDB docs about directConnection
1 parent 698241a commit 6e1213b

File tree

1 file changed

+32
-11
lines changed

1 file changed

+32
-11
lines changed
Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { MongoDBContainer, StartedMongoDBContainer } from "./mongodb-container";
1+
import { MongoDBContainer } from "./mongodb-container";
22
import mongoose from "mongoose";
33

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

11-
await checkMongo(mongodbContainer);
11+
// directConnection: true is required as the testcontainer is created as a MongoDB Replica Set.
12+
const db = mongoose.createConnection(mongodbContainer.getConnectionString(), { directConnection: true });
13+
14+
// You can also add the default connection flag as a query parameter
15+
// const connectionString = `${mongodbContainer.getConnectionString()}?directConnection=true`;
16+
// const db = mongoose.createConnection(connectionString);
17+
18+
const fooCollection = db.collection("foo");
19+
const obj = { value: 1 };
20+
21+
const session = await db.startSession();
22+
await session.withTransaction(async () => {
23+
await fooCollection.insertOne(obj);
24+
});
25+
26+
expect(
27+
await fooCollection.findOne({
28+
value: 1,
29+
}),
30+
).toEqual(obj);
1231

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

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

24-
await mongoose.disconnect();
25-
await mongodbContainer.stop();
26-
});
27-
// }
44+
// You can also add the default connection flag as a query parameter
45+
// const connectionString = `${mongodbContainer.getConnectionString()}?directConnection=true`;
46+
// const db = mongoose.createConnection(connectionString);
2847

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

@@ -39,7 +56,11 @@ describe("MongodbContainer", () => {
3956
expect(
4057
await fooCollection.findOne({
4158
value: 1,
42-
})
59+
}),
4360
).toEqual(obj);
44-
}
61+
62+
await mongoose.disconnect();
63+
await mongodbContainer.stop();
64+
});
65+
// }
4566
});

0 commit comments

Comments
 (0)