Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to develop with mongodb offline?

Tags:

mongodb

go

I am developing a webapp with a backend in Golang and DB using mongo. However, I realise that whenever I do not have an internet connection or use public wifi, I cannot connect to my Mongo Atlas. This will cause my local server to panic and I will have to rely on only certain connections to run my app and self test.

Is there any way I can continue development without a proper internet connection? Any help is appreciated. Below is my code to initializing the DB.

main.go

func main() {
    fmt.Println("hello world")
    ctx := context.Background()
    config.InitializeConfig()
    dbDisconnect := database.InitializeDatabase(ctx)

    defer func() {
        if err := dbDisconnect(ctx); err != nil {
            panic(err)
        }
    }()

     // Other Initializations and App logic
}

initializeDb.go

var clientInstance *mongo.Client

func InitializeDatabase(ctx context.Context) func(ctx context.Context) error {

    serverAPI := options.ServerAPI(options.ServerAPIVersion1)
    opts := options.Client().ApplyURI(getDBLink()).SetServerAPIOptions(serverAPI)

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

    dc := client.Disconnect

    clientInstance = client

    if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{Key: "ping", Value: 1}}).Err(); err != nil {
        panic(err)
    }
    fmt.Println("Pinged your deployment. You successfully connected to db")

    return dc
}
like image 862
jellypancake Avatar asked Dec 15 '25 06:12

jellypancake


1 Answers

You can setup a local MongoDB with the same structure as the remote MongoDB. Then you can test it without internet connection. (Install docker and then enter the following command sudo docker run -p 27017:27017 mongo, this will setup a mongodb instance on port 27017 or without docker following the steps in the following website MongoDB Installation.

I would also recommend you to use environment variables for the host and port of the MongoDB and then you won't need to change the code, only the environment variables to connect to local or remote database.

like image 118
epilif3sotnas Avatar answered Dec 16 '25 20:12

epilif3sotnas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!