因此,我正在尝试使用正式的mongodb go驱动程序(之前使用过mgo),但遇到了麻烦。我正在尝试封送/取消封送自定义类型,这显然在默认情况下不起作用。该文档有点缺乏。基本上我想做的是这样:
cur, err := mongo.Collection("coll").Find(ctx, bson.M{})
if err != nil {
return err
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var el X
err := cur.Decode(&el)
if err == nil {
// Do whatever...
}
}
if err = cur.Err(); err != nil {
return err
}
有没有办法做到这一点,或者现在它完全缺少此功能?我知道它仍然是Beta版本,但是没有太多选择。
编辑:
举例说明我想做什么:
no decoder found for Z
我得到的错误是:package examples
import (
"context"
"testing"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo"
)
type X struct {
Color string `json:"color" bson:"color"`
Y Z `bson:"y"`
}
type Z interface {
echo() string
}
func (x X) echo() string {
return x.Color
}
func TestFindCars(t *testing.T) {
var err error
var client *mongo.Client
var collection *mongo.Collection
var cur mongo.Cursor
var ctx = context.Background()
if client, err = mongo.Connect(ctx, "mongodb://localhost/so?replicaSet=replset"); err != nil {
t.Fatal(err)
}
collection = client.Database("so").Collection(collectionName)
collection.InsertOne(ctx, bson.M{"color": "Red", "y": 12})
if cur, err = collection.Find(ctx, bson.M{}); err != nil {
t.Fatal(err)
}
if err != nil {
t.Fatal(err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var el X
if err = cur.Decode(&el); err != nil {
t.Fatal(err)
}
t.Log(el.echo())
}
if err = cur.Err(); err != nil {
t.Fatal(err)
}
}
测试示例:
var maxDepth = function(root) {
if (!root) {
return 0
}
let depth = 0;
let arr=[root];
while (arr.length) {
let arrlength=arr.length;
for (let i=0;i<arrlength;i++) {
let curr=arr.shift();
arr.push(...curr.children);
}
depth++;
}
return depth;
};
答案 0 :(得分:0)
这里是使用您的示例的完整示例,并且运行良好。
package examples
import (
"context"
"testing"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo"
)
type X struct {
Color string `json:"color" bson:"color"`
Y Z
}
type Z interface {
echo() string
}
func (x X) echo() string {
return x.Color
}
func TestFindCars(t *testing.T) {
var err error
var client *mongo.Client
var collection *mongo.Collection
var cur mongo.Cursor
var ctx = context.Background()
if client, err = mongo.Connect(ctx, "mongodb://localhost/so?replicaSet=replset"); err != nil {
t.Fatal(err)
}
collection = client.Database("so").Collection(collectionName)
collection.InsertOne(ctx, bson.M{"color": "Red"})
if cur, err = collection.Find(ctx, bson.M{}); err != nil {
t.Fatal(err)
}
if err != nil {
t.Fatal(err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var el X
if err = cur.Decode(&el); err != nil {
t.Fatal(err)
}
t.Log(el.echo())
}
if err = cur.Err(); err != nil {
t.Fatal(err)
}
}
测试
$ GOCACHE=off go test -v -run TestFindCars
=== RUN TestFindCars
--- PASS: TestFindCars (0.09s)
find2_test.go:49: Red
PASS