Golang Mongodb bson字符串切片数组解组错误

问题描述 投票:1回答:1

在我的MongoDB数据库集合中,我像这样存储产品:

{
   "_id":{
      "$oid":"5e87388e622a7a973148cf15"
   },
   "tags":[
      "foo",
      "bar",
      "baz"
   ]
}

我想这样解组:

type Product struct {
    Tags          []string           `bson:"tags" json:"tags"`
}

以及当我尝试检索它时

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("correct-address"))
if err != nil {
    log.Fatal(err)
    return
}
collection := client.Database("products").Collection("products")

cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
    log.Fatal(err)
    fmt.Fprint(w, err)
    return
}
defer cursor.Close(ctx)

products := []Product{}
for cursor.Next(ctx) {
    var nextOne Product
    err := cursor.Decode(&nextOne)
    if err != nil {
        log.Fatal(err)
    }
    products = append(products, nextOne)
}

我收到错误

cannot decode document into []string

有人知道我在做什么错吗?

mongodb go
1个回答
0
投票

有人知道我在做什么错吗?

错误消息cannot decode document into []string表示您要解码的字段tags代替了数组,而不是数组。代替:

{"tags": ["foo", "bar", "baz"]}

您具有以下内容:

{"tags": {"foo": "bar"}}

我建议探索该集合,也许集合中有许多文档的架构与预期不同。

© www.soinside.com 2019 - 2024. All rights reserved.