Can i do unique constraint on some attribute not the id


#1

is there some way to create a unique constraint on document attribute not the id, something like: a credit card number on the user document which i want it to be unique.


Unique constraint with document lookup and counter question
#2

no there isn’t a notion of “unique constraint” in Couchbase. However you could use the concept of a “lookup document”: create an additional document which key is a derivative of the field you want to be unique. For example
email::sherlockDOTholmesATmycroftsoftDOTcom would be the lookup document for the following user:

{ "userId": 10041240,
  "login": "shomes",
  "fname": "Sherlock",
  "lname": "Holmes",
  "company": "Mycroft Soft",
  "email": "sherlock.holmes@mycroftsoft.com"
}

(so, prefix with email::, append the email with all . replaced with DOT and @ replaced by AT => that’s your lookup key)

From there on, if another user wants to register with the same email, use the same procedure to derive the lookup key and try to use the create operation. It will fail because the key already exist, and you then know the registration should be cancelled (thanks, optimistic locking).

Note: I’ve used a different example as yours, because Credit Card information is very sensitive data, and you should do your maximum to avoid storing it in your own system (ALWAYS prefer using the services of a specialized, well-recognized, third party payment provider).
:credit_card: + :computer: :beetle: = :money_with_wings: :scream_cat:


#3

LGTM if couchbase do not have the unique constraint feature, i really do not store credit card number it is just for give an example. And Very appreciate for your answer.


#4

Just curious if there are any plans to add such a feature in the future (unique constraints) versions?
The approach you suggested maybe works ok for one unique field, but in reality for user type documents we might want to have constraints for user email, username, mobile phone number and maybe something else. Obviously the more constraints you need the more cumbersome and bugs prone this approach becomes. Would be so much easier if the database could guarantee the uniqueness.


#5

@dmitryb Unfortunately I don’t think that is a design goal of Couchbase, which was never built to ensure field constraints (as having fields isn’t even a given in Couchbase…).
I’ll ping @cihangirb here nonetheless, so that the PM team is aware of your question/suggestion.


#6

Thanks @simonbasle and @dmitryb - Great ask. We do have plans on constraints around in future but I don’t have a timeline for this capability. The only uniqueness constraint at the moment is on document keys.

Tracking this here if you’d like to refer to it in future.
https://issues.couchbase.com/browse/MB-19776
thanks
-cihan