dpw63348 2018-10-08 15:27
浏览 574
已采纳

将字符串切片转换为BSON数组

I am trying to insert an array into a MongoDB instance using Go. I have the [] string slice in Go and want to convert it into a BSON array to pass it to the DB using the github.com/mongodb/mongo-go-driver driver.

var result bson.Array
    for _, data := range myData {
        value := bson.VC.String(data)
        result.Append(value)
}

This loops over each element of my input data and tries to append it to the BSON array. However the line with the Append() fails with panic: document is nil. How should I do this conversion?

  • 写回答

1条回答 默认 最新

  • doushifang4382 2018-10-08 15:30
    关注

    Edit: The code in the question and this answer is no longer relevant because the bson.Array type was deleted from the package. At the time of this edit, the bson.A and basic slice operations should be used to construct arrays.

    Use the factory function NewArray to create the array:

    result := bson.NewArray()
    for _, data := range myData {
            value := bson.VC.String(data)
            result.Append(value)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 zabbix6.4与frp如何进行联动
  • ¥15 如何使用Echarts制作途中时间序列表
  • ¥15 图论相关的数学问题,共10个
  • ¥15 EtherCAT的问题,创建一个XML文件
  • ¥15 微信公众号羽毛球自动抢定场程序制作
  • ¥15 Fluent UDF 编写
  • ¥15 xcode开发的macos应用,如何使窗口居中显示?
  • ¥20 统信uos升级apt后启动失败
  • ¥15 求指导储层饱和度及含水率测井解释
  • ¥200 建三维地震工区写入sgy到指定目录