duanqiongchong0354 2019-09-03 17:53
浏览 219
已采纳

在正式的mongoDB驱动程序中,ObjectID自动设置为“ 0…0”

I'm trying to save user entries in a MongoDB database with Go. Users should get an ID automatically. I'm using the offical MongoDB Go driver.

My sources were especially https://vkt.sh/go-mongodb-driver-cookbook/ and https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial.

Struct looks like this:

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"`
}

Setting up the database (connection works) and signing up users (based on an HTTP-Request r with a user in it's body):

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

When I enter the first user, it is added to the collection, but the ID looks like this: _id:ObjectID(000000000000000000000000)

If I now want to enter another user, I get the following error:

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

So it seems like again ObjectID 000000000000000000000000 is assigned.

I expected the ID to be automatically set to a unique value for each entry.

Do I have to manually set the ID or how can I assign unique IDs to users?

  • 写回答

2条回答 默认 最新

  • doumi1099 2019-09-03 18:29
    关注

    Per the documentation you linked, you must set the object ID yourself when using structs:

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

    The examples before that using bson.M don't need to specify an ID because they don't send the _id field at all; with a struct, the field is being sent with its zero value (as you've seen).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器