couchdb-best-practices icon indicating copy to clipboard operation
couchdb-best-practices copied to clipboard

How to handle unique Fields in Documents except _id

Open h4cc opened this issue 9 years ago • 3 comments

Common case it to have unique Usernames/Emails in a document. How can be assured with couchdb, that the values of these fields stay unique?

A Idea i found interesting on stackoverflow, lets discuss the approach: http://stackoverflow.com/questions/1541239/unique-constraints-in-couchdb

h4cc avatar Jul 08 '15 18:07 h4cc

I also would have recommend the approach described in that stackoverflow answer but did not try it yet nor have thought about that method in depth.

Do you have a concrete use case?

jo avatar Jul 09 '15 08:07 jo

Have not yet implemented any of these ideas. Will give feedback when i succeded, or failed...

h4cc avatar Jul 09 '15 10:07 h4cc

Current state:

I tried having own documents for unique field, like unique usernames for user accounts.

It can be done using a user document containing {username: alice} and a view using emit(doc.username, null), but that would not guarantee uniqueness. If that does not need to be strongly enforced, it might be the easiest way to go.

A other implementation is using a "unique-doc" for that, like {_id: user-username-alice, username: alice, user_id: user-1234}. Having such a document per username can guarantee its uniqueness. To query by username then, could either be done doing two request to couchdb, like first GET /foo/user-username-alice and then GET /foo/user-1234. Or a view for the unique usernames doing a "JOIN" could be used like emit(doc.username, {_id: doc.user_id}), that would be reducing to a single query to a view.

What bothered me was having too much documents, whose only use was to ensure uniqueness or N-M relations. Is there a universal hint that says try to reduce the number of documents or rather try to reduce the number of changes to/size of existing ones?

h4cc avatar Jul 30 '15 08:07 h4cc