【问题标题】:How to remove the primitive.E composite literal uses unkeyed fields error?如何删除primitive.E复合文字使用未键控字段错误?
【发布时间】:2021-08-11 08:10:42
【问题描述】:

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

【问题讨论】:

    标签: mongodb go mongo-go composite-literals


    【解决方案1】:

    您看到的是 lint 警告,而不是编译器错误。 bson.Dprimitive.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,
        },
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2018-04-19
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      相关资源
      最近更新 更多