为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
SMILET 2023-07-17 17:08:34
我正在尝试使用 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 Usererr := 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?
查看完整描述

2 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

您必须在使用 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根本不发送字段;对于结构,该字段将以其零值发送(如您所见)。


查看完整回答
反对 回复 2023-07-17
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

如果设置了文档_id,mongodb将在插入过程中使用该_id作为文档,并且不会生成。您必须忽略它,或者使用primitive.NewObjectID()手动设置它。



查看完整回答
反对 回复 2023-07-17
  • 2 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信