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