登录
首页 >  Golang >  Go问答

在Golang中使用MongoDB插入数据

来源:stackoverflow

时间:2024-03-19 15:21:30 449浏览 收藏

在 Go 语言中使用 MongoDB 插入数据时,使用结构体作为插入内容可能导致数据无法正确插入。这是因为结构体的字段默认情况下对其他包不可见。为了解决这个问题,需要显式导出结构体的字段,以便其他包可以访问它们。这可以通过在结构体字段前加上“`bson`”标签来实现,例如: ```go 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"` } ```

问题内容

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

插入操作成功执行。


解决方案


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

好了,本文到此结束,带大家了解了《在Golang中使用MongoDB插入数据》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>