DEV Community

Discussion on: Go and MongoDB: Building a CRUD API from Scratch

Collapse
 
aquibpy profile image
Mohd Aquib

To manage MongoDB migrations in Go without using JSON, use the migrate library with the MongoDB driver and write migrations programmatically in Go. Here’s a concise guide:

Install dependencies:

   go get -u -d github.com/golang-migrate/migrate/cmd/migrate
   go get -u github.com/golang-migrate/migrate/v4/database/mongodb
   go get -u github.com/golang-migrate/migrate/v4/source/file
Enter fullscreen mode Exit fullscreen mode

Create a migration in Go:

   package main

   import (
       "github.com/golang-migrate/migrate/v4"
       "github.com/golang-migrate/migrate/v4/database/mongodb"
       "github.com/golang-migrate/migrate/v4/source/file"
       "log"
   )

   func main() {
       mongoURL := "mongodb://localhost:27017/mydatabase"

       source, err := (&file.File{}).Open("file://path/to/migrations")
       if err != nil {
           log.Fatal(err)
       }

       database, err := mongodb.WithInstance(mongoURL, &mongodb.Config{})
       if err != nil {
           log.Fatal(err)
       }

       m, err := migrate.NewWithInstance(
           "file",
           source,
           "mongodb",
           database,
       )
       if err != nil {
           log.Fatal(err)
       }

       if err := m.Up(); err != nil && err != migrate.ErrNoChange {
           log.Fatal(err)
       }

       log.Println("Migrations applied successfully!")
   }
Enter fullscreen mode Exit fullscreen mode

Write migrations as Go scripts.

This setup allows you to handle MongoDB migrations using Go code.