英文:
How to remove the primitive.E composite literal uses unkeyed fields error?
问题
在这段代码中,我正在尝试在MongoDB数据库中添加一个新字段。但是在update
变量中出现了一个问题,即go.mongodb.org/mongo-driver/bson/primitive.E composite literal uses unkeyed fields
。我不知道该怎么办。
错误出现在代码的这部分。
{"$set", bson.D{
primitive.E{Key: fieldName, Value: insert},
}},
代码
func Adddata(fieldName, insert string) {
// 设置客户端选项
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// 连接到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)
}
}
英文:
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)
}
}
答案1
得分: 3
你看到的是一个lint警告,而不是编译器错误。bson.D
是一个primitive.E
的切片,当列出切片中的primitive.E
值时,你使用了一个无键的字面量:
update := bson.D{
{"$set", bson.D{
primitive.E{Key: fieldName, Value: insert},
}},
}
为了消除警告,请在结构字面量中提供键:
update := bson.D{
{Key: "$set", Value: bson.D{
primitive.E{Key: fieldName, Value: insert},
}},
}
请注意,你还可以使用bson.M
值来提供更新文档,这样更简单和可读:
update := bson.M{
"$set": bson.M{
fieldName: insert,
},
}
英文:
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,
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论