为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
肥皂起泡泡 2022-05-23 17:39:17
在我的 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有谁知道我在这里做错了什么?=============== 已解决事实证明,我的集合中有一个包含“标签”的文档:{}
查看完整描述

1 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

有谁知道我在这里做错了什么?

错误消息cannot decode document into []string表明,tags您尝试解码的字段不是一个数组,而是一个文档。代替 :

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

您有以下内容:

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

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


查看完整回答
反对 回复 2022-05-23
  • 1 回答
  • 0 关注
  • 356 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号