我正在尝试使用 Go 将用户条目保存在 MongoDB 数据库中。用户应该自动获得一个ID。我正在使用官方 MongoDB Go 驱动程序。
我的资料来源尤其是https://vkt.sh/go-mongodb-driver-cookbook/和https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial。
结构看起来像这样:
type User struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Fname string `json:"fname" bson:"fname"`
Lname string `json:"lname" bson:"lname"`
Mail string `json:"mail" bson:"mail"`
Password string `json:"password" bson:"password"`
Street string `json:"street" bson:"street"`
Zip string `json:"zip" bson:"zip"`
City string `json:"city" bson:"city"`
Country string `json:"country" bson:"country"`
}
设置数据库(连接有效)并注册用户(基于r主体中包含用户的 HTTP 请求):
ctx := context.Background()
uriDB := "someURI"
clientOptions := options.Client().ApplyURI(uriDB)
client, err := mongo.Connect(ctx, clientOptions)
collection := client.Database("guDB").Collection("users")
...
var user User
err := json.NewDecoder(r.Body).Decode(&user)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, err := collection.InsertOne(ctx, user)
...
当我输入第一个用户时,它被添加到集合中,但 ID 如下所示: _id:ObjectID(000000000000000000000000)
如果我现在想输入另一个用户,我会收到以下错误:
multiple write errors: [{write errors: [{E11000 duplicate key error collection: guDB.users index: _id_ dup key: { : ObjectId('000000000000000000000000') }}]}, {<nil>}]
所以看来 ObjectID 又000000000000000000000000被分配了。
我希望每个条目的 ID 自动设置为唯一值。
我是否必须手动设置 ID 或者如何为用户分配唯一的 ID?
aluckdog
慕雪6442864
相关分类