第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何創(chuàng)建一個(gè) mongo db 包

如何創(chuàng)建一個(gè) mongo db 包

Go
慕無(wú)忌1623718 2022-06-01 17:36:01
我想建立一個(gè)基礎(chǔ)設(shè)施,它是項(xiàng)目的一個(gè)包。以便其他開(kāi)發(fā)人員可以導(dǎo)入此包對(duì)數(shù)據(jù)庫(kù)執(zhí)行 CRUD 操作。但是我在測(cè)試過(guò)程中遇到了一個(gè)錯(cuò)誤:type Students struct {    Name      string    Age int}type InsertOneResult struct {    InsertedID interface{}}func dbGetOne(coll, document interface{}) (*InsertOneResult, error) {...}func dbUpdateOne(coll, document interface{}) (*InsertOneResult, error) {    ...}func dbDeleteOne(coll, document interface{}) (*InsertOneResult, error) {    ...}func dbInsertOne(coll, document interface{}) (*InsertOneResult, error) {    res, err := coll.InsertOne(context.TODO(), document)    if err != nil {        log.Fatal(err)    }    return &InsertOneResult{InsertedID: res[0]}, err}func main() {    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://<user>:<password>@<host>:<port>/<dbname>"))    if err != nil {        log.Fatal(err)    }    ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)    err = client.Connect(ctx)    if err != nil {        log.Fatal(err)    }    coll := client.Database("db").Collection("students")    data := Students{"Amy", 10}    res, err := dbInsertOne(coll, data)    if err != nil {        log.Fatal(err)    }    fmt.Printf("inserted document with ID %v\n", res.InsertedID)}這是錯(cuò)誤:./main.go:24:18: coll.InsertOne undefined (type interface {} is interface with no methods)有沒(méi)有辦法解決這個(gè)問(wèn)題?提前致謝。
查看完整描述

1 回答

?
哈士奇WWW

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊

嘿,看起來(lái)錯(cuò)誤可能來(lái)自類(lèi)型轉(zhuǎn)換問(wèn)題。解決方案是在函數(shù)中明確定義collas的類(lèi)型。這允許編譯器在編譯時(shí)找出輸入的結(jié)構(gòu),而不必依賴(lài)抽象接口。*mongo.CollectiondbInsertOne()


func dbInsertOne(coll *mongo.Collection, document interface{}) (*InsertOneResult, error) {

    res, err := coll.InsertOne(context.TODO(), document)

    if err != nil {

        log.Fatal(err)

    }

    return &InsertOneResult{InsertedID: res.InsertedID}, err

}

我會(huì)進(jìn)一步建議,document如果可能的話,第二個(gè)參數(shù)也應(yīng)該是一個(gè)類(lèi)型化的已知術(shù)語(yǔ)。例如


func dbInsertOne(coll *mongo.Collection, document Students)

靜態(tài)類(lèi)型將有很大幫助并消除任何混亂。


查看完整回答
反對(duì) 回復(fù) 2022-06-01
  • 1 回答
  • 0 關(guān)注
  • 148 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)