dongwu4834 2014-04-08 07:14
浏览 72
已采纳

如何构造并通过bson文件-Go语言?

I am using Go and mongoDB in my project and mgo is to connect to connect MongoDB.

I am having following document this is to be inserted in the 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"
     }
  }

I have created the BSON document as above.

I have two packages

  1. account.go

  2. dbEngine.go

account.go is used to create BSON document and send the BSON document to dbEngine.go

dbEngine.go is used to establish connection to MongoDB and insert the document. while passing BSON document to dbEngine.go

dbEngine.Insert(bsonDocument);

In dbEngine.go i am having method

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

Error : panic: Can't marshal interface {} as a BSON document.

Whether interface{} is not to be used for BSON document.

I am new to Go. Any suggestion or help will be grateful

  • 写回答

2条回答 默认 最新

  • duanjiashai9140 2014-04-08 08:52
    关注

    You don't need to generate a BSON document yourself.
    Let say in account.go you will have an account struct:

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

    Then in dbEngine.go your Insert function:

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

    And then, some where in your app:

    acc := Account{}
    acc.Id = bson.NewObjectId()
    acc.BalanceAmount = 3
    
    dbEngine.Insert(&acc);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误