mongodb - 如何删除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)
}
}
解决方案
您看到的是 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,
},
}
推荐阅读
- python - 我可以让 for 循环永远运行吗?(Python)
- oracle-adf - 收到所需文件集后触发触发
- python - 以特定顺序将图像加载到列表中
- android-studio - 使用 Android Studio 进行 Oculus 开发的最佳示例应用?
- angular - Angular 拦截器请求因 strict-origin-when-cross-origin 而失败
- kotlin - 是否可以在 scope.cancel 之后接收发射?
- java - 我正在制作一个 Minecraft Mod,我收到错误“mods.toml 缺少 modid mymod 的元数据”
- ubuntu - 如何使用 redis.conf 在 ubuntu 上启动多个 redis 服务
- haskell - 获取数据类型中的键的最佳方法是什么?
- graphql - 在 GraphQl 中定义解析器