【发布时间】:2020-03-30 10:46:26
【问题描述】:
我有一个运行 MongoDB 的 AWS 实例。我正在尝试做一个小的 db 操作,当下面包含的文件被写入单个 go 文件时,它似乎可以工作。当我尝试拆分它时,出现以下错误
在调用 Execute 之前,插入操作必须有一个部署集
拆分文件如下所示
connect.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.")
}
main.go
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
【问题讨论】:
-
你在使用 go 模块吗?您如何编译/运行您的应用程序?
-
不,我没有使用 go 模块。我使用命令编译它:
go run main.go -
@SidharthV,我希望你解决了你的问题。如果没有阅读 this article 。不过,如果你不明白,请告诉我,我会写一个详细的答案。
标签: mongodb go amazon-ec2