Search code examples
mongodbgomongo-go

How to InsertOne to mongo database


I have tried to insert a document into a mongo database. I have tried with the code I have written below but I am not able to insert the struct data. Am using mongo-driver. Could anyone help me find why I am not able to perform insert in the RegisterNFInstance handler function?

Here is my code.

const (
    COLLECTION = "nrfcoll"
)

db  *mongo.Database

func  Connect() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }

    defer func() {
        if err = client.Disconnect(ctx); err != nil {
            panic(err)
        }
    }()
    // Check the connection
    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatal(err)
    }
    // Collection types can be used to access the database
    db = client.Database("profiledb")
    fmt.Println("Successfully connected to MongoDB!")
}


type  NfProfile struct {

    NfInstanceId string `json:"nfInstanceId,omitempty" bson:"nfInstanceId,omitempty"`

    NfInstanceName string `json:"nfInstanceName,omitempty" bson:"nfInstanceName,omitempty"`

    NfType string `json:"nfType" bson:"nfType"`

    NfStatus string `json:"nfStatus,omitempty" bson:"nfStatus"`

}

func Insert(ctx context.Context, nfinstance NfProfile) bool {
    _, err := db.Collection(COLLECTION).InsertOne(ctx, nfinstance)
    if err != nil {
        return false
    }
    return true
}

func respondWithJson(response http.ResponseWriter, code int, payload interface{}) {
    res, err := json.Marshal(payload)
    if err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(err.Error()))
        return
    }
    response.Header().Set("Content-Type", "application/json; charset=UTF-8")
    response.WriteHeader(code)
    response.Write([]byte(res))

}


func RegisterNFInstance(response http.ResponseWriter, request *http.Request) {

    var nfProfile  NfProfile
    
    if request.Header.Get("Content-Type") != "application/json" {
        WriteError(response, ErrStatusUnsupportedMediaType)
        return
    }
        err := json.NewDecoder(request.Body).Decode(&nfProfile)
        if err != nil {
            WriteError(response, ErrBadRequest)
            return
        }
        defer request.Body.Close()

        ctx := context.Background()

        success := Insert(ctx, nfProfile)
        if !success {
            WriteError(response, ErrInternalServer)
            return
        } 

     respondWithJson(response, http.StatusCreated, nfProfile)
}

Solution

  • Your Connect() function contains a deferred call which calls client.Disconnect(). Which means before your Connect() returns the connection will already be closed.

    Remove this disconnecting code:

    defer func() {
        if err = client.Disconnect(ctx); err != nil {
            panic(err)
        }
    }()