首页 > 解决方案 > 如何删除primitive.E复合文字使用未键控字段错误?

问题描述

在这段代码中,我试图在 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) {
    // 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)
    }
}

标签: mongodbgomongo-gocomposite-literals

解决方案


您看到的是 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,
    },
}

推荐阅读