G
G
Glitchmorphosis2019-12-26 15:25:27
go
Glitchmorphosis, 2019-12-26 15:25:27

How to handle duplicate key collection error?

I am using MongoDB. Code for adding data to the collection:

type User struct {
  Firstname        string             `json:"firstname" bson:"firstname"`
  Lastname         *string            `json:"lastname,omitempty" bson:"lastname"`
  Username         string             `json:"username" bson:"username"`
  RegistrationDate primitive.DateTime `json:"registrationDate" bson:"registrationData"`
  LastLogin        primitive.DateTime `json:"lastLogin" bson:"lastLogin"`
}


var client *mongo.Client

func AddUser(response http.ResponseWriter, request *http.Request) {
  collection := client.Database("hattip").Collection("user")
  var user User
  _ = json.NewDecoder(request.Body).Decode(&user)
  insertResult, err := collection.InsertOne(context.TODO(), user)
  if err != nil {
                // здесь нужно понять какая именно ошибка.
    fmt.Println("Error on inserting new user", err)
    response.WriteHeader(http.StatusPreconditionFailed)
  } else {
    fmt.Println(insertResult.InsertedID)
    response.WriteHeader(http.StatusCreated)
  }

}

func main() {
  client = GetClient()
  err := client.Ping(context.Background(), readpref.Primary())
  if err != nil {
    log.Fatal("Couldn't connect to the database", err)
  } else {
    log.Println("Connected!")
  }

  router := mux.NewRouter()
  router.HandleFunc("/person", AddUser).Methods("POST")
  err = http.ListenAndServe("127.0.0.1:8080", router)
  if err == nil {
    fmt.Println("Server is listening...")
  } else {
    fmt.Println(err.Error())
  }

}

func GetClient() *mongo.Client {
  clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
  client, err := mongo.NewClient(clientOptions)

  if err != nil {
    log.Fatal(err)
  }
  err = client.Connect(context.Background())
  if err != nil {
    log.Fatal(err)
  }
  return client
}

If I add a record with the username field, the data of which is already in the database, then I get -
Error on inserting new user multiple write errors: [{write errors: [{E11000 duplicate key error collection: hattip.user index: username_unique dup key: { username: "dd" }}]}, {}]
in line . There is already an entry with the string dd in the username field , and the username field is a unique index. I need to somehow understand that the error is exactly E11000 (duplicate key error collection) . So far, I have thought of comparing err with the entire error string that occurs when a unique field is duplicated, but this is not at all correct. Is it possible to somehow access the error code from the err object , or maybe there are some other ways? I also found a verification option using the mgo package , but in order to use it, you will have to study a new package, rewrite the connection, and so on, but it looks good:fmt.Println("Error on inserting new user", err)



if mgo.IsDup(err) {
                err = errors.New("Duplicate name exists for the shorturl")
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2019-12-26
@Glitchmorphosis

https://jira.mongodb.org/browse/GODRIVER-972

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question