MongoDB collection.Watch()编译并停止运行
我是MongoDB的新手,我尝试过使用“go.MongoDB.org/mongo driver/mongo”lib中的collection.Watch()。和来自的代码。然后我构建并运行它,并立即停止 我试着一次又一次地跑,它也停止了跑。我在MongoDB collection.Watch()编译并停止运行,mongodb,go,changestream,Mongodb,Go,Changestream,我是MongoDB的新手,我尝试过使用“go.MongoDB.org/mongo driver/mongo”lib中的collection.Watch()。和来自的代码。然后我构建并运行它,并立即停止 我试着一次又一次地跑,它也停止了跑。我在go-run-main.go和/testStreams之间切换,它仍然停止运行 这是我编辑过的代码 clientOptions := options.Client(). ApplyURI("mongodb://localhost:27
go-run-main.go
和/testStreams
之间切换,它仍然停止运行
这是我编辑过的代码
clientOptions := options.Client().
ApplyURI("mongodb://localhost:27017/test")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatalf("Failed to create the new client: %v", err)
}
ctx := context.Background()
if err := client.Connect(ctx); err != nil {
log.Printf("Failed to open client connection: %v", err)
}
defer client.Disconnect(ctx)
coll := client.Database("test").Collection("streams")
var pipeline interface{}
for {
cur, err := coll.Watch(ctx, pipeline)
if err != nil {
log.Fatalf("Watch error: %v", err)
}
defer cur.Close(ctx)
log.Println(cur)
for cur.Next(ctx) {
elem := CSElem{}
if err := cur.Decode(elem); err != nil {
log.Fatalf("Decode error: %v", err)
}
log.Println(elem)
}
if err := cur.Err(); err != nil {
log.Fatalf("Error detected: %v", err)
}
}
当我编辑时,会出现错误
2019/08/07 13:46:39未能打开客户端连接:拓扑为
已连接或正在连接退出状态1
如何修复???如评论中所述,在建立连接之前,需要先使用v1+创建一个新的
客户端
实例。例如:
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/test")
client, err := mongo.NewClient(clientOptions)
if err != nil {log.Fatal(err)}
// Timed out after 10 seconds of trying to connect
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil { log.Fatal(err)}
您好,欢迎来到StackOverflow。当由
Watch
返回的err
变量不返回nil
时,请将其作为log.Fatal
输出。如果再次运行该程序,现在应该会看到一条错误消息。请将该错误消息添加到您的问题中。我刚刚编辑了我的问题,错误出现在2019/08/07 13:46:39未能打开客户端连接:拓扑已连接或连接退出状态1Great。现在,您使用的是哪个版本的mongo-go-driver
?如果您使用的是v1+,请使用client,err:=mongo.NewClient(options.client().ApplyURI()mongodb://localhost:27017)
而不是您的mongo.Connect
。另外,你能从同一台机器上通过mongo
shell连接到MongoDB吗?我的版本是v1.1.0,然后我改为你的建议代码并运行,它开始平滑!!。所以我尝试在mongo中添加一些数据,它有一些错误,比如“Decode error:argument to Decode必须是指向类型的指针,但是得到了{{}{}{}{ObjectID(“000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000!!非常感谢@WanBachtiar!!!不客气。