mongodb

package module
v0.24.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 3 Imported by: 38

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MongoDBContainer

type MongoDBContainer struct {
	testcontainers.Container
}

MongoDBContainer represents the MongoDB container type used in the module

func RunContainer

RunContainer creates an instance of the MongoDB container type

Example
package main

import (
	"context"
	"fmt"

	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/modules/mongodb"
)

func main() {
	// runMongoDBContainer {
	ctx := context.Background()

	mongodbContainer, err := mongodb.RunContainer(ctx, testcontainers.WithImage("mongo:6"))
	if err != nil {
		panic(err)
	}

	// Clean up the container
	defer func() {
		if err := mongodbContainer.Terminate(ctx); err != nil {
			panic(err)
		}
	}()
	// }

	state, err := mongodbContainer.State(ctx)
	if err != nil {
		panic(err)
	}

	fmt.Println(state.Running)

}
Output:
true
Example (Connect)
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/modules/mongodb"
)

func main() {
	// connectToMongo {
	ctx := context.Background()

	mongodbContainer, err := mongodb.RunContainer(ctx, testcontainers.WithImage("mongo:6"))
	if err != nil {
		panic(err)
	}

	// Clean up the container
	defer func() {
		if err := mongodbContainer.Terminate(ctx); err != nil {
			panic(err)
		}
	}()

	endpoint, err := mongodbContainer.ConnectionString(ctx)
	if err != nil {
		panic(err)
	}

	mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(endpoint))
	if err != nil {
		panic(err)
	}
	// }

	err = mongoClient.Ping(ctx, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(mongoClient.Database("test").Name())

}
Output:
test

func (*MongoDBContainer) ConnectionString

func (c *MongoDBContainer) ConnectionString(ctx context.Context) (string, error)

ConnectionString returns the connection string for the MongoDB container

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL