使用 mongo-go-driver,如何有效地从 WriteError 中检索重复的字段名称?

ime*_*tuk 5 go mongodb mongo-go

我的收藏中有三个独特的索引。当用户不小心插入字段中重复的数据时B,我如何知道重复项来自字段B

在违反唯一索引约束时, mongo-go-driver 行为返回 err WriteException,它基本上由 WriteError 数组和一些其他对象组成。

WriteError本身(来自 mongo-go-driver):

// WriteError is an error that occurred during the execution of a write operation. This error type is only returned as part
// of a WriteException or BulkWriteException.
type WriteError struct {
    // The index of the write-in the slice passed to an InsertMany or BulkWrite operation that caused this error.
    Index int

    Code    int
    Message string
}
Run Code Online (Sandbox Code Playgroud)

在调试会话期间,我发现 WriteError 的值为:

{
    Index: 0
    Code: 11000
    Message: E11000 duplicate key error collection: auth.example index: B_1 dup key: { : "default-role-external-user" }
}
Run Code Online (Sandbox Code Playgroud)

我知道我总是可以通过 (11000) 推断出唯一约束违规Code,但库没有提供单个字段来检索导致重复错误的字段名称。

我知道我总是可以将解析Message字符串作为最后的手段,但考虑到 Golang 和 MongoDB 已经共存了很长一段时间,而且我确信我不是唯一遇到这个问题的人,我期待更强大和更高效的解决方案检索导致重复错误的字段名称的方法,我还没有找到。

icz*_*cza 1

简短而令人悲伤的答案是,目前官方 mongo-go 驱动程序没有更好的方法。

  • @Eklavya 提问者发布了一个经过充分研究的问题,几乎列出了他/她的可行选项,并询问是否有更简单的方法。但没有。所以我认为目前这个答案就是“有它的意义”。 (2认同)