微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何insertOne到mongo数据库

如何解决如何insertOne到mongo数据库

我试图将文档插入mongo数据库。 我尝试使用下面编写的代码,但是无法插入结构数据。 我正在使用mongo驱动程序。 谁能帮助我找到为什么我无法在RegisterNFInstance处理函数中执行插入操作?

这是我的代码

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)
}

解决方法

您的Connect()函数包含一个延迟的调用,该调用调用client.Disconnect()。这意味着在您的Connect()返回之前,连接已经关闭。

删除此断开连接的代码:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。