1

In this code, I am trying to add a new field in the MongoDB database. But it is giving me a problem in the update variable and that is go.mongodb.org/mongo-driver/bson/primitive.E composite literal uses unkeyed fields. I don't know what to do.

The error is on this part of the code.

{"$set", bson.D{
     primitive.E{Key: fieldName, Value: insert},
}},

Code

func Adddata(fieldName, insert string) {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    collection := client.Database("PMS").Collection("dataStored")

    filter := bson.D{primitive.E{Key: "password", Value: Result1.Password}}

    update := bson.D{
        {"$set", bson.D{
            primitive.E{Key: fieldName, Value: insert},
        }},
    }

    _, err = collection.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        log.Fatal(err)
    }
}
icza
  • 389,944
  • 63
  • 907
  • 827
Qora bhai
  • 47
  • 6

1 Answers1

3

What you see is a lint warning, but not a compiler error. bson.D is a slice of primitive.E, and you use an unkeyed literal when listing the primitive.E values of the slice:

update := bson.D{
    {"$set", bson.D{
        primitive.E{Key: fieldName, Value: insert},
    }},
}

To get rid of the warning, provide the keys in the struct literal:

update := bson.D{
    {Key: "$set", Value: bson.D{
        primitive.E{Key: fieldName, Value: insert},
    }},
}

Note that alternatively you may use a bson.M value to provide the update document, it's simpler and more readable:

update := bson.M{
    "$set": bson.M{
        fieldName: insert,
    },
}
icza
  • 389,944
  • 63
  • 907
  • 827