How to construct and pass bson document - Go lang?

2019-01-29 03:08发布

问题:

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

回答1:

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);


回答2:

The mgo driver uses the labix.org/v2/mgo/bson package to handle BSON encoding/decoding. For the most part, this package is modelled after the standard library encoding/json package.

So you can use structs and arrays to represent objects. For example,

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 {
    ...
}

You can now create values of this type to pass to mgo.



标签: mongodb go