mongodb之使用 mongo-go-driver,如何有效地从 WriteError 中检索重复的字段名称
Renyi-Fan
阅读:60
2025-06-02 22:19:02
评论:0
我的收藏中有三个唯一索引。当用户不小心在 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
}
在调试 session 期间,我发现 WriteError 的值是:
{
Index: 0
Code: 11000
Message: E11000 duplicate key error collection: auth.example index: B_1 dup key: { : "default-role-external-user" }
}
我知道我总是可以通过
Code (11000) 推断出唯一的约束违规,但是库没有提供单个字段来检索导致重复错误的字段名称。
我知道我总是可以解析
Message 字符串作为最后的手段,但考虑到 Golang 和 MongoDB 已经共存了很长时间,而且我确信我不是唯一遇到这个问题的人,我期待更强大和检索导致重复错误的字段名称的有效方法,我还没有找到。
请您参考如下方法:
简短而令人难过的答案是,目前官方 mongo-go 驱动程序没有更好的方法。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



