繁体   English   中英

在Golang中的mongodb中插入struct

[英]Inserting struct in mongodb in Golang

我试图在mongo数据库中插入一个结构。

type SecretsStruct struct {
   UserID string `bson:"userid" json:"userid"`
   secretOne string `bson:"secret_one" json:secret_one`
   secretTwo string `bson:"secret_two" json:secret_two`
   secretThree string `bson:"secret_three" json:secret_three`
 }

func (c *SecretsStruct) SetSecrets(userId string, encryptedKeys   
      [][]byte){
   c.UserID = userId
   c.secretOne = hex.EncodeToString(encryptedKeys[0])
   c.secretTwo = hex.EncodeToString(encryptedKeys[1])
   c.secretThree = hex.EncodeToString(encryptedKeys[2])
   log.Printf("This is the c %s", c)
 }

 g := SecretsStruct{}
 g.SetSecrets(userStruct.UserID, encryptedKeys)
 err = secretCollection.Insert(g)
 if err != nil {
      panic(err)
  }

我尝试插入与机密相对应的字节数组,但没有帮助。 填充到相应插入操作中的结果是:

{'_id': ObjectId('5b80117c118c660aaa0c87c2'),
'userid': 'eb19d220-ef13-43aa-8a7f-f78637718000'}

另一方面,如果我尝试插入具有地图但没有结构的相同数据。

secretCollection.Insert(bson.M{"userid": userStruct.UserID,
    "secret_one": encryptedKeys[0],
    "secret_two": encryptedKeys[1],
    "secret_three": encryptedKeys[2]})

插入操作成功执行。

您必须导出您的struct字段,以便另一个包(在本例中为mgo)可以访问它们:

type SecretsStruct struct {
    UserID string `bson:"userid" json:"userid"`
    SecretOne string `bson:"secret_one" json:secret_one`
    SecretTwo string `bson:"secret_two" json:secret_two`
    SecretThree string `bson:"secret_three" json:secret_three`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM