Skip to content
On this page

MongoDB

Оглавление

Клиент Go

В yabbi-ssp используется официальный клиент Mongo Go Driver.

Совет: чтобы получить представление о том, как использовать клиент Mongo Go Driver, ознакомьтесь с руководством по началу работы.

Подключение к кластеру

Подключение к кластеру MongoDB:

go
import (
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

credential := options.Credential{
    Username: Username,
    Password: Password,
})

opts := options.Client().
     SetAuth(credential).
     SetHosts(hosts).
     SetReplicaSet(replicaSet).
     SetConnectTimeout(connectionTimeout).
     SetMaxPoolSize(maxPoolSize).
     SetMaxConnecting(maxConnecting).
     SetReadPreference(readpref.Secondary())

client, err := mongo.Connect(ctx, opts)
if err != nil {
    // error handling.
}

err = client.Ping(ctx)

Тестирование

Docker compose

docker-compose.yaml:

yaml
version: '3'

services:
  mongo:
    image: 'bitnami/mongodb:latest'
    restart: always
    environment:
      - ALLOW_EMPTY_PASSWORD=yes
    ports:
      - '27017:27017'

mongodb_test.go:

go
import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/requure"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type teardownFunc func(t *testing.T, collections ...string)

func newMongoDatabase(t *testing.T, database string) (*mongo.Database, teardownFunc) {
    const uri = "mongodb://localhost:27017/"
    opts := options.Client().ApplyURI(uri)

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx, opts)
    require.NoError(t, err)
    require.NoError(t, client.Ping(ctx, nil))

    db := client.Database(database)

    return db, func(t *testing.T, collections ...string) {
        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
        defer cancel()

        for _, collection := range collections {
            err := db.Collection(collection).Drop(ctx)
            assert.NoError(t, err)
        }

        assert.NoError(t, db.Drop(ctx))
        assert.NoError(t, client.Disconnect(ctx))
    }
}

func TestConnect(t *testing.T) {
    db, teardown := newMongoDatabase(t, "test")
    t.Cleanup(func() {
        teardown(t, "collectionName")
    })

    // ...
}