我的收藏中有三个独特的索引。当用户不小心插入字段中重复的数据时B
,我怎么知道重复项来自字段B
?
在违反唯一索引约束时,mongo-go-driver 行为返回错误WriteException
,它基本上由 WriteError 数组和一些其他对象组成。
The 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
}
在调试会话期间,我发现 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
string 作为最后的手段,但考虑到 Golang 和 MongoDB 已经共存了很长一段时间,而且我确信我不是唯一遇到这个问题的人,我期待更强大和更有效的方法来检索字段名称,从而导致重复错误,我还没有找到。
简短而令人悲伤的答案是,目前官方 mongo-go 驱动程序没有更好的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)