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 已经共存了很长一段时间,而且我确信我不是唯一遇到这个问题的人,我期待更强大和更高效的解决方案检索导致重复错误的字段名称的方法,我还没有找到。
简短而令人悲伤的答案是,目前官方 mongo-go 驱动程序没有更好的方法。
| 归档时间: |
|
| 查看次数: |
799 次 |
| 最近记录: |