MongoDB Atlas集群Golang插入结构体切片接口上下文取消,当前拓扑

huangapple go评论77阅读模式
英文:

mongodb atlas cluster golang insert struct slice interface context canceled, current topology

问题

当我将一组文档插入到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)
	}

}
英文:

When I insert a set of documents into a MongoDB Atlas collection I get the following error message:

2021/12/23 09:37:03 server selection error: context canceled, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: cluster-attitude-shard-00-00.o7pjk.mongodb.net:27017, Type: Unknown }, { Addr: cluster-attitude-shard-00-01.o7pjk.mongodb.net:27017, Type: Unknown }, { Addr: cluster-attitude-shard-00-02.o7pjk.mongodb.net:27017, Type: Unknown }, ] }

I use the next code:

interfaz_slice := ToInterfaceSlice(students)

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

The function "ToInterfaceSlice" recieve a slice of structs and return a slice of interface

I do not understand where I am making a mistake

Thanks in advance

New part of question:

File fragment "main.go":

func main() {

	var students []data.TypeStudent

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

	students = data.LeerFichero(absPath)

	data.ConectaBD()

	data.InsertaColleccionEstudiantes(students)

}

File fragment "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
}

File fragment "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)
	}

}

答案1

得分: 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)
    }
}()

// 开始插入多个文档
coll := client.Database("insertDB").Collection("haikus")
docs := []interface{}{
    bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "没有字节,没有问题。只需在MongoDB中插入一个文档"}},
    bson.D{{"title", "Showcasing a Blossoming Binary"}, {"text", "二进制数据,通过GridFS安全存储。将数据存储在桶中"}},
}

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

英文:

Information is not sufficient. Check if IP is whitelisted or not. Also specify which context you are using. You can try with context.TODO().

I tried and it's working fine.

Make sure your connection is successful. Also close the connection using defer.

Here is the sample code you can try with this :

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

For better understanding please refer this link : https://raw.githubusercontent.com/mongodb/docs-golang/master/source/includes/usage-examples/code-snippets/insertMany.go

huangapple
  • 本文由 发表于 2021年12月23日 17:14:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/70459911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定