Golang Mongodb bson字符串切片数组解组错误
在我的MongoDB数据库集合中,我存储的产品如下:Golang Mongodb bson字符串切片数组解组错误,mongodb,go,Mongodb,Go,在我的MongoDB数据库集合中,我存储的产品如下: { "_id":{ "$oid":"5e87388e622a7a973148cf15" }, "tags":[ "foo", "bar", "baz" ] } 我想这样说: type Product struct { Tags []string `bson:"tags" json:"tags"` } 当我试图找回它的时候
{
"_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
有人知道我做错了什么吗
==============
解决
事实证明,我在一个集合中有一个文档将具有“标记”:{}
有人知道我做错了什么吗
错误消息无法将文档解码为[]字符串
表示您试图解码的字段标记
不是数组,而是文档。而不是:
{“标记”:[“foo”,“bar”,“baz”]}
您具有以下功能:
{“标记”:{“foo”:“bar”}
我建议探索这个集合,也许集合中有许多文档的模式与预期的不同 首先,谢谢你的回答,我们离成功又近了一步。查看我的mongodb收集文档,我将其作为问题的第一个元素显示。我的文档中有一个字符串数组(对吗?)。因此,go驱动程序认为“标签”是一个文档,而实际上“标签”是一个数组。我是对的还是错的?你的一个例子是正确的,但是你的收藏中还有其他文件吗?它们都有相同的结构吗?是的,正如你所说,这是一份文件。我现在觉得自己很愚蠢。