登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-17 16:27:28 321浏览 收藏

**如何处理 MongoDB 重复唯一索引错误** MongoDB 中的唯一索引用于确保集合中的字段值唯一。当尝试插入具有重复唯一索引值的新记录时,将引发错误。本指南将介绍如何处理这种错误,以确保应用程序行为正确。

问题内容

我正在使用 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索引: username_unique dup key: { 用户名: "dd" }}]}, {}]

fmt.println("error on inserting new user", 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

最直接的选项是使用 mongo.isduplicatekey(error) 函数 here

好了,本文到此结束,带大家了解了《如何处理重复唯一索引错误?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>