Convert a string slice to a BSON array

Issue

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?

Solution

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

Answered By – Bayta Darell

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.