How to access MongoDB from different package?

Hey in the website I am trying to code I am using MongoDB. When I put everything in main package and start the database in main function everything works perfectly but when I seperated my code into packages it crashes whenever I access the handler that uses GetDBCollection() function.

So how can I access to database collection inside the handlers package ?

Note:Sorry for my poor english.

Here is a part my code:
handlers.go


package handlers

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/onurcevik/DuyuruTV/database"
	"github.com/onurcevik/DuyuruTV/model"
	"go.mongodb.org/mongo-driver/bson"
	"golang.org/x/crypto/bcrypt"
)

func RegisterEndpoint(w http.ResponseWriter, r *http.Request) {

	w.Header().Set("content-type", "application/json")
	var person model.Person
	var responseResult model.ResponseResult
	_ = json.NewDecoder(r.Body).Decode(&person)
	collection, _ := database.GetDBCollection()
	if err != nil {
		responseResult.Error = err.Error()
		json.NewEncoder(w).Encode(responseResult)
		return
	}

	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	result, _ := collection.InsertOne(ctx, person)
	json.NewEncoder(w).Encode(result)
	
}

database.go

package database

import (
	"context"
	"log"
	"time"

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

var client *mongo.Client

func GetDBCollection() (*mongo.Collection, error) {
	ctx, err := context.WithTimeout(context.Background(), 30*time.Second)
	client, _ = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

	if err != nil {
		log.Fatal(err)
	}
	// Check the connection
	/*
		client.Ping(context.TODO(), nil)
		if err != nil {
			log.Fatal(err)
		}
	*/
	collection := client.Database("duyurutv").Collection("people")
	return collection, nil
}

main.go

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/onurcevik/DuyuruTV/handlers"
)

//"go.mongodb.org/mongo-driver/bson/primitive"
//	"go.mongodb.org/mongo-driver/mongo"

func main() {
	fmt.Println("Starting the application...")
	router := mux.NewRouter()
	router.HandleFunc("/", handlers.LoginPageHandler).Methods("GET")
	router.HandleFunc("/login", handlers.LoginEndpoint).Methods("POST")
	router.HandleFunc("/register", handlers.RegisterEndpoint).Methods("POST")
	router.HandleFunc("/people", handlers.GetPeopleEndpoint).Methods("GET")
	router.HandleFunc("/addcontent", handlers.AddContentEndpoint).Methods("GET")
	http.ListenAndServe(":8080", router)

}

collection.InsertOne and mongo.Connect both return errors but you don’t handle these. Just assigning them to underscore variable. Could this be the problem?

Nope I just solve the problem by calling this function in main

func StartDatabase() {
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	client, _ = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.