Determining which unique constraint caused INSERT

2019-09-13 01:47发布

问题:

I have a document collection in ArangoDB that has multiple unique indexes. When inserting a new document, the insert could fail because of any of the unique indexes. Is there a way to easily figure out which field(s) in the document caused the insert to fail?

For example, take a collection that stores user data. Unique indexes on both the "username" and "email" fields mean that an insert could fail if either of those fields are duplicated.

Error messages are non-specific:

{ 
    error: true,
    errorMessage: 'unique constraint violated (while executing)',
    code: 409,
    errorNum: 1210
}

The long way around would be to input/update these unique fields separately to know for certain which field violated the unique constraint. Or try retrieving documents that match our input values to identify if there would be a collision before trying to insert. I just have a feeling that there must be a simpler way.

Is there a way to return the field name along with the error? Or am I approaching the problem from entirely the wrong angle?

Would really appreciate any thoughts or suggestions. Thanks.

回答1:

I'm sorry, there is currently no smart way to achieve this. The only way to handle this today, is to do a subsequent select with a FILTER to the values you tried to insert:

FOR doc IN collection
  FILTER doc.firstindexed = 'firstvalue'
      OR doc.secondindexed = 'secondvalue'
    RETURN doc