1

What is the best practice in Couchrest for implementing something like a unique constraint. I could do this with the _id , but what if I want to implemnet it on multiple fields, not necesarily as a composite, but even separately. Say for e.g. I want email ID and the username both to be unique, just to point out an example.

Is there a best practice around doing this without using the _id field.

Sam Wilder
  • 869
  • 1
  • 9
  • 21

1 Answers1

2

The only way to enforce uniqueness in CouchDB is with _id field.

I believe the best practice for other things which need uniqueness is to allow the client to store it, and then check for uniqueness as an external program (or thread, or cron job, etc.) and then react to that. For example, a map/reduce view can easily produce a count of identical field values, thus searching for fields with count > 1 is easy. Next, correct any duplicates you find.

You can even treat this as a simple workflow with request/reject or request/approve steps. Store the initial document, but it is not official until e.g. it has "confirmed":true. It only receives a confirmation after your offline checker has performed the above checks.

I think in real-world applications, people developing with CouchDB postpone uniqueness constraints, for the same reason people try not to prematurely optimize. You will probably notice that 99% of users always input a unique email address anyway, so trying to enforce uniqueness all the time is just creating a problem for yourself that you don't need.

JasonSmith
  • 72,674
  • 22
  • 123
  • 149