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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?