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

我正在尝试使用 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?


SMILET
浏览 177回答 2
2回答

aluckdog

您必须在使用 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(),})使用之前的示例bson.M不需要指定 ID,因为它们_id根本不发送字段;对于结构,该字段将以其零值发送(如您所见)。

慕雪6442864

如果设置了文档_id,mongodb将在插入过程中使用该_id作为文档,并且不会生成。您必须忽略它,或者使用primitive.NewObjectID()手动设置它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go