猿问

Mongo FindOne 和界面{}

我正在尝试创建一个采用接口而不是特定类型并调用 FindOne 函数的函数。有谁知道为什么 printFirstTrainerByInterface 函数不能正常工作?


我正在使用官方的 Go Mongo-Driver 和来自mongodb-go-driver-tutorial 的示例片段。


package main


import (

    "context"

    "fmt"

    "log"


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

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

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

)


type Trainer struct {

    Name string

    Age  int

    City string

}


var db *mongo.Database


func main() {

    opts := options.Client().ApplyURI("mongodb://localhost:27017")

    client, err := mongo.Connect(context.TODO(), opts)

    if err != nil {

        log.Fatal(err)

    }

    err = client.Ping(context.TODO(), nil)

    if err != nil {

        log.Fatal(err)

    }

    db = client.Database("test")

    insertTestDocument()


    var result Trainer

    printFirstTrainer(result)


    var result2 Trainer

    printFirstTrainerByInterface(&result2)

}


func insertTestDocument() {

    ash := Trainer{"Ash", 10, "Pallet Town"}

    res, err := db.Collection("trainers").InsertOne(context.TODO(), ash)

    if err != nil {

        log.Fatal(err)

    }

    fmt.Println("Inserted a test document: ", res.InsertedID)

}


func printFirstTrainer(result Trainer) {

    collection := db.Collection("trainers")

    err := collection.FindOne(context.TODO(), bson.M{}).Decode(&result)

    if err != nil {

        log.Fatal(err)

    }

    fmt.Printf("Found a single document: %+v\n", result)

}


func printFirstTrainerByInterface(result interface{}) {

    collection := db.Collection("trainers")

    err := collection.FindOne(context.TODO(), bson.M{}).Decode(&result)

    if err != nil {

        log.Fatal(err)

    }

    fmt.Printf("Found a single document: %+v\n", result)

}

输出:


Inserted a test document:  ObjectID("5e8216f74f41a13f01061d61")

Found a single document: {Name:Ash Age:10 City:Pallet Town}

Found a single document: [{Key:_id Value:ObjectID("5e8216f74f41a13f01061d61")} {Key:name Value:Ash} {Key:age Value:10} {Key:city Value:Pallet Town}]



qq_花开花谢_0
浏览 193回答 1
1回答

GCT1015

您将要解码的结构的地址作为接口传递。您必须将其作为参数传递给解码,而不是接口的地址。尝试:err := collection.FindOne(context.TODO(), bson.M{}).Decode(result)
随时随地看视频慕课网APP

相关分类

Go
我要回答