在collection.InsertOne时就有自带的方法可以获取插入时的ObjectId
func (p *DbUtil) InsetOne(table string, v interface{}) (interface{}, error) {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
username, password, hosts := GetDbConfig()
clientOptions := options.Client().SetHosts(hosts)
if len(username) > 0 && len(password) > 0 {
clientOptions.SetAuth(options.Credential{Username: username, Password: password})
}
client, err := mongo.Connect(ctx, clientOptions)
//client, err := mongo.Connect(ctx, options.Client().ApplyURI(GetDbUri()))
defer func() {
err = client.Disconnect(ctx)
if err != nil {
fmt.Println("Client Close Fail")
}
}()
if err != nil {
fmt.Println("Connect Db Fail")
return nil, err
}
collection := client.Database(DB_NAME).Collection(table)
//_, err = collection.InsertOne(ctx, bson.M{"name": "john", "nick": "n04"})
result, err := collection.InsertOne(ctx, v)
return result.InsertedID, err
InsertedID