mongodb - 在 Golang 的 mongodb 中插入结构

标签 mongodb go

我正在尝试在 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)
  }

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

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

另一方面,如果我尝试使用 map 插入相同的数据但没有结构。

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

插入操作执行成功。

最佳答案

您必须导出您的结构字段,以便另一个包(在本例中为 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`
}

关于mongodb - 在 Golang 的 mongodb 中插入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006453/

相关文章:

python - 从 python 并行写入 MongoDb 集合

php - 用于实时 ajax 的 MongoDB?

不要在 Atom 中工作

go - 如何在不使用字段名称作为字符串的情况下获取字段的标签?

go - 双重检查 golang 中的锁定 - 为什么需要 mutex.RLock()?

javascript - 如何比较 Mongoose 对象和 JSON 对象?

node.js - 使用mongodb本地创建数据库的流程

amazon-web-services - 将 Go 项目部署到 AWS Lambda 时出现 "PathError"

ruby-on-rails - 如何使用 Mongoid 执行 runCommand?

go - 条件超时