【问题标题】:How to construct and pass bson document - Go lang?如何构建和传递 bson 文档 - Go lang?
【发布时间】:2014-04-08 07:14:14
【问题描述】:

我在我的项目中使用Go和mongoDB,mgo是连接MongoDB

我有以下要插入到 MongoDB 中的文档

 {
     "_id" : ObjectId("53439d6b89e4d7ca240668e5"),
     "balanceamount" : 3,
     "type" : "reg",
     "authentication" : {
       "authmode" : "10",
       "authval" : "sd",
       "recovery" : {
          "mobile" : "sdfsd",
          "email" : "sds@gmail.com"
        }
      },
     "stamps" : {
        "in" : "x",
        "up" : "y"
     }
  }

我已经创建了上面的 BSON 文档。

我有两个包

  1. account.go

  2. dbEngine.go

account.go 用于创建 BSON 文档并将 BSON 文档发送到 dbEngine.go

dbEngine.go 用于建立与 MongoDB 的连接并插入文档。 同时将 BSON 文档传递给 dbEngine.go

dbEngine.Insert(bsonDocument);

在 dbEngine.go 我有方法

func Insert(document interface{}){
 //stuff
}

错误:恐慌:无法将接口 {} 编组为 BSON 文档。

interface{} 是否不用于 BSON 文档。

我是Go 的新手。任何建议或帮助将不胜感激

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    您不需要自己生成 BSON 文档。
    假设在 account.go 中你将有一个 account 结构:

    type Account struct {
      Id bson.ObjectId `bson:"_id"` // import "labix.org/v2/mgo/bson"
      BalanceAmount int
      // Other field
    }
    

    然后在 dbEngine.go 你的插入函数:

    func Insert(document interface{}){
      session, err := mgo.Dial("localhost")
      // check error
      c := session.DB("db_name").C("collection_name")
      err := c.Insert(document)
    }
    

    然后,在您的应用中的某个位置:

    acc := Account{}
    acc.Id = bson.NewObjectId()
    acc.BalanceAmount = 3
    
    dbEngine.Insert(&acc);
    

    【讨论】:

      【解决方案2】:

      mgo 驱动程序使用labix.org/v2/mgo/bson 包来处理 BSON 编码/解码。在大多数情况下,这个包是根据标准库encoding/json 包建模的。

      因此您可以使用结构和数组来表示对象。例如,

      type Document struct {
          Id bson.ObjectId `bson:"_id"`
          BalanceAmount int `bson:"balanceamount"`
          Type string `bson:"type"`
          Authentication Authentication `bson:"authentication"`
          Stamps Stamps `bson:"stamps"`
      }
      type Authentication struct {
          ...
      }
      type Stamps struct {
          ...
      }
      

      您现在可以创建此类型的值以传递给mgo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        • 2021-03-20
        • 2014-01-17
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 2013-08-06
        相关资源
        最近更新 更多