mongrator

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

README

Mongrator

Mongrator is a Go package that automatically runs MongoDB schema migrations at application startup.

Prerequisites

  • Use bson tags in your struct fields to define schema mappings.
  • Schemas must be defined as Go structs (not other types).

Limitations

  • Pointer Support: This package does not handle pointers in schemas. If your schema uses pointers, Mongrator might not work as expected.

Installation

To install Mongrator, run the following command:

go get github.com/RonanzinDev/mongrator
Usage
package main

import (
	"context"
	"time"

	"github.com/RonanzinDev/mongrator"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type User struct {
	Name     string    `json:"name" bson:"name"`
	Addrees  Addrees   `json:"address" bson:"address"`
	Contacts []Contact `json:"contacts" bson:"contacts"`
}
type Addrees struct {
	Street string `json:"street" bson:"street"`
	Number int    `json:"number" bson:"number"`
}

type Contact struct {
	Email  string  `json:"email" bson:"email"`
	Number float64 `json:"number" bson:"number"`
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) // Adjust the context as needed
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	db := client.Database("YOUR_DATABASE")
	migrator := mongrator.New(db)
	migrator.RegisterSchema("users", User{})
	migrator.RunMigrations()
}

Configuration

You can customize Mongrator's behavior with optional configurations:

migrator := mongrator.New(db).ShouldCreateCollection().ShouldSaveMigrations()
Avaliable options
  • ShouldCreateCollection: Determines whether a collection should be created when registering a schema
  • ShouldSaveMigrations: // Enables saving the migration log in the database
Contributing

If you encounter any issues, feel free to open an Issue :)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Mongrator added in v1.0.6

type Mongrator struct {
	// contains filtered or unexported fields
}

func New

func New(database *mongo.Database) *Mongrator

Initialize the migrator

func (*Mongrator) RegisterSchema added in v1.0.6

func (m *Mongrator) RegisterSchema(collection string, schema any)

Registers a schema and its corresponding collection for automatic migration during application startup.

func (*Mongrator) RunMigrations added in v1.0.6

func (m *Mongrator) RunMigrations()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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