【问题标题】:mongodb atlas cluster golang insert struct slice interface context canceled, current topologymongodb atlas cluster golang insert struct slice interface context 取消,当前拓扑
【发布时间】:2022-01-24 07:39:14
【问题描述】:

当我将一组文档插入 MongoDB Atlas 集合时,我收到以下错误消息:

2021/12/23 09:37:03 服务器选择错误:上下文已取消,当前拓扑:{类型:ReplicaSetNoPrimary,服务器:[{地址:cluster-attitude-shard-00-00.o7pjk.mongodb .net:27017,类型:未知},{地址:cluster-attitude-shard-00-01.o7pjk.mongodb.net:27017,类型:未知},{地址:cluster-attitude-shard-00-02.o7pjk .mongodb.net:27017,类型:未知},]}

我使用下一个代码:

interfaz_slice := ToInterfaceSlice(students)

_, err := coleccion.InsertMany(ctx, interfaz_slice)

函数“ToInterfaceSlice”接收一个结构切片并返回一个接口切片

我不明白我在哪里犯了错误

提前致谢

问题的新部分:

文件片段“main.go”:

func main() {

    var students []data.TypeStudent

    absPath, _ := filepath.Abs("data/students.csv")

    students = data.LeerFichero(absPath)

    data.ConectaBD()

    data.InsertaColleccionEstudiantes(students)

}

文件片段“students.go”:

type TypeStudent struct {
    FirstName string `bson:"first_name" json:"first_name"`
    LastName  string `bson:"last_name" json:"last_name"`
    Class     string `bson:"class" json:"class"`
}

func ToInterfaceSlice(lista []TypeStudent) []interface{} {
    iface := make([]interface{}, len(lista))
    for i := range lista {
        iface[i] = lista[i]
    }
    return iface
}

文件片段“basedatos.go”:

func ConectaBD() {

    cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
    err = cliente_local.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer cancelar()

    mongo_cliente = cliente_local.Database("attitude")

    log.Println("[+]Connected to MongoDB Atlas")

}

func InsertaColleccionEstudiantes(students []TypeStudent) {

    coleccion = mongo_cliente.Collection("students")

    interfaz_slice := ToInterfaceSlice(students)

    log.Println("[+]A slice of interfaces are inserted directly into MONGODB")

    _, err := coleccion.InsertMany(ctx, interfaz_slice)

    if err != nil {
        log.Fatal(err)
    }

}

【问题讨论】:

  • 错误不在 Golang 客户端代码中,而是在您正在运行的 MongoDB 集群中。您是否尝试过连接 mongo shell 并执行查询?
  • 我可以连接 mongosh:link
  • 我看了视频,你应该从 mongo shell 运行相同的查询,并请分享其余代码、连接处理程序等。

标签: go mongodb-atlas


【解决方案1】:

信息不足。检查IP 是否被列入白名单。还要指定您正在使用的上下文。你可以试试context.TODO()

我试过了,效果很好。

确保您的连接成功。同时使用defer关闭连接。

这是您可以尝试的示例代码:

client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
    if err != nil {
        panic(err)
    }
    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            panic(err)
        }
    }()

    // begin insertMany
    coll := client.Database("insertDB").Collection("haikus")
    docs := []interface{}{
        bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "No bytes, no problem. Just insert a document, in MongoDB"}},
        bson.D{{"title", "Showcasing a Blossoming Binary"}, {"text", "Binary data, safely stored with GridFS. Bucket the data"}},
    }

    result, err := coll.InsertMany(context.TODO(), docs)
    if err != nil {
        panic(err)
    }

为了更好的理解,请参考这个链接:https://raw.githubusercontent.com/mongodb/docs-golang/master/source/includes/usage-examples/code-snippets/insertMany.go

【讨论】:

  • 您的代码片段有效。我的代码必须有任何错误
  • 太棒了,只是为了添加 context.TODO 作品:_, err := coleccion.InsertMany(context.TODO(), interfaz_slice)。非常感谢你,圣诞快乐!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
相关资源
最近更新 更多