Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 如何处理重复的唯一索引错误?_Mongodb_Go - Fatal编程技术网

Mongodb 如何处理重复的唯一索引错误?

Mongodb 如何处理重复的唯一索引错误?,mongodb,go,Mongodb,Go,我在用MongoDB。将数据添加到集合的代码: type User struct { Firstname string `json:"firstname" bson:"firstname"` Lastname *string `json:"lastname,omitempty" bson:"lastname"` Username string `json:"user

我在用MongoDB。将数据添加到集合的代码:

  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 {
    // here i need to get the kind of error.
    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
}
如果我添加的记录的用户名已经存在于数据库中,我会得到-

插入新用户时出错多个写入错误:[{写入错误: [{E11000重复键错误集合:hattip.user索引: 用户名\唯一dup密钥:{用户名:“dd”}]},{}]

fmt.Println(“插入新用户时出错”,err)
行中,
username
字段中带有字符串
dd
的记录已经存在,
username
字段是唯一的索引

我想确定错误是E11000错误(重复的关键错误集合)

到目前为止,我将
err
与出现在唯一字段副本上的整个错误字符串进行比较,但这是完全错误的。是否有方法从
err
对象获取错误代码,或者有其他方法解决此问题

另外,我发现了
mgo
软件包,但要正确使用它,我必须学习它,重写当前代码等等,但老实说,它看起来不错:

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

根据驱动程序文档,
InsertOne
可能返回一个
WriteException
,因此您可以检查错误是否为
WriteException
,如果是,则检查其中的
WriteErrors
。每个
WriteError
都包含一个错误代码

if we, ok:=err.(WriteException); ok {
   for _,e:=range we.WriteErrors {
      // check e.Code
   }
}
您可以基于此编写
IsDup