使用官方 mongoDB 驱动程序,ObjectID 自动设置为“0...0”

Ste*_*anK 5 go mongodb

我正在尝试使用 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"`
}
Run Code Online (Sandbox Code Playgroud)

设置数据库(连接有效)并注册用户(基于 HTTP 请求,r其中包含一个用户):

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)
...

Run Code Online (Sandbox Code Playgroud)

当我输入第一个用户时,它被添加到集合中,但 ID 如下所示: _id:ObjectID(000000000000000000000000)

如果我现在想输入另一个用户,则会出现以下错误:

multiple write errors: [{write errors: [{E11000 duplicate key error collection: guDB.users index: _id_ dup key: { : ObjectId('000000000000000000000000') }}]}, {<nil>}]
Run Code Online (Sandbox Code Playgroud)

因此,似乎再次000000000000000000000000分配了 ObjectID 。

我希望 ID 自动设置为每个条目的唯一值。

我是否必须手动设置 ID 或如何为用户分配唯一 ID?

Adr*_*ian 8

根据您链接的文档,您必须在使用 structs 时自己设置对象 ID

_, err := col.InsertOne(ctx, &Post{
    ID:        primitive.NewObjectID(),    // <-- this line right here
    Title:     "post",
    Tags:      []string{"mongodb"},
    Body:      `blog post`,
    CreatedAt: time.Now(),
})
Run Code Online (Sandbox Code Playgroud)

使用之前的示例bson.M不需要指定 ID,因为它们根本不发送_id字段;对于结构体,该字段以其零值发送(如您所见)。