on the find field. I created a struct to use in the decode and the document is returned without issue. Can anyone explain what this warning is about? Here is the full function
func getMovie(c *gin.Context) {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
uri := os.Getenv("MONGODB_URI")
if uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("axelrod").Collection("movies")
title := "Back to the Future"
var movie Movie
err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&movie)
if err == mongo.ErrNoDocuments {
fmt.Printf("No document was found with the title %s\n", title)
return
}
if err != nil {
panic(err)
}
jsonData, err := json.MarshalIndent(movie, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", jsonData)
c.JSON(http.StatusOK, movie)
}
Hey @tapiocaPENGUIN, thanks for the question! The Go Driver team has also noticed that the default linters installed with the VSCode Go plugin warns about unkeyed fields in composite literals when using the BSON document literal syntax used in most of the Go Driver examples. While it’s reasonably safe to ignore that warning for the bson.E types (we consider changing the order and type of fields in bson.E an API breaking change that would only happen in a different major version of the Go Driver), it’s still annoying to get those linter warnings. Check out GODRIVER-2271, which is a proposal to modify the BSON document literal declaration syntax in a way that doesn’t cause linter warnings in most editors.
As far as an immediate solution, you can get around those linter warnings by using keyed fields in the bson.E literals. For example:
bson.D{{Key: "title", Value: title}}
However, that’s fairly verbose, so many people chose to accept the linter warnings in exchange for more terse syntax.
We don’t currently have a timeline for implementing any of the proposed BSON document literal syntax improvements, but please comment on GODRIVER-2271 if you have an opinion about any of them!