MongoDB Module
MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
Install
npm install @testcontainers/mongodb --save-dev
Examples
it("should work using default version 4.0.1", async () => {
const mongodbContainer = await new MongoDBContainer().start();
// 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();
});
it("should work using version 6.0.1", async () => {
const mongodbContainer = await new MongoDBContainer("mongo:6.0.1").start();
// 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();
});