在我的 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
有谁知道我在这里做错了什么?
=============== 已解决
事实证明,我的集合中有一个包含“标签”的文档:{}
开心每一天1111
相关分类