使用mongo-go-driver,如何有效地从WriteError检索重复的字段名称? [英] With mongo-go-driver, how do I efficiently retrieve duplicated field name from WriteError?

查看:43
本文介绍了使用mongo-go-driver,如何有效地从WriteError检索重复的字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的收藏夹中有三个唯一索引.当用户在字段 B 中意外插入具有重复项的数据时,我怎么知道重复项来自字段 B ?

在违反唯一索引约束的情况下,mongo-go-driver行为返回err WriteException ,该错误基本上由WriteError和其他对象组成.

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

I have three unique indexes in my collection. When user accidentally insert a data having a duplicate in the field B, how do I know that the duplication comes from field B?

On unique index constraint violation, mongo-go-driver behavior is returning err WriteException, which basically consist of an array of WriteError and some other object.

The WriteError itself (from 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的值为:

During a debug session, I found out that the value of the WriteError is :

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

我知道我总是可以通过 Code (11000)来推断出唯一约束冲突,但是该库没有提供单个字段来检索引起重复错误的字段名称.

I know I always can infer the unique constraint violation via the Code (11000), but the library didn't provide a single field to retrieve the field name causing duplication error.

我知道我总是可以将 Message 字符串解析为最后的手段,但是考虑到Golang和MongoDB已经共存很长一段时间了,我敢肯定我不是唯一遇到这种情况的人问题,我期望有一种更健壮,更有效的方法来检索导致重复错误的字段名称,这是我尚未找到的.

I know I can always parse the Message string as the last resort, but considering that Golang and MongoDB have been coexisting a long while and I'm sure I'm not the only one encountering this issue, I'm expecting the more robust and efficient way to retrieve the field name causing duplication error, which I'm yet to find.

推荐答案

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

The short and saddening answer is that currently there isn't a better way with the official mongo-go driver.

这篇关于使用mongo-go-driver,如何有效地从WriteError检索重复的字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆