我有一个正在运行 MongoDB 的 AWS 实例。我正在尝试执行一个小型数据库操作,当下面包含的文件写入单个 go 文件中时,该操作似乎可以工作。当我尝试拆分它时,出现以下错误
在调用 Execute 之前,插入操作必须具有部署集
分割后的文件如下
连接.go
package db
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var Client1 mongo.Client
func Connect() {
// Set client options
clientOptions := options.Client().ApplyURI("remote_url")
// Connect to MongoDB
Client1, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = Client1.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
}
func main() {
fmt.Println("Connection to MongoDB done.")
}
主程序
package main
import (
"context"
"fmt"
"log"
"db"
"go.mongodb.org/mongo-driver/bson"
)
// You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
func main() {
db.Connect()
collection := db.Client1.Database("test2").Collection("trainers")
_ = collection
fmt.Println("Created collection", _)
ash := Trainer{"Ash", 10, "Pallet Town"}
// misty := Trainer{"Misty", 10, "Cerulean City"}
// brock := Trainer{"Brock", 15, "Pewter City"}
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult)
err = db.Client1.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
它们被放置在以下结构中
/src -> main.go
/src -> /db/connect.go
茅侃侃
MMMHUHU
相关分类