Skip to content

MongoDB

Install

1
npm install @testcontainers/mongodb --save-dev

Examples

These examples use the following libraries:

Choose an image from the container registry and substitute IMAGE.

Execute a query

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
await using container = await new MongoDBContainer(image).start();

const db = mongoose.createConnection(container.getConnectionString(), { directConnection: true });

const obj = { value: 1 };
const collection = db.collection("test");
await collection.insertOne(obj);

const result = await collection.findOne({ value: 1 });
expect(result).toEqual(obj);

await db.close();

With credentials

1
2
3
4
await using container = await new MongoDBContainer(IMAGE)
  .withUsername("customUsername")
  .withPassword("customPassword")
  .start();