Adam Carter
Adam Carter

Reputation: 4844

Getting document(s) based on an attribute in CouchDB (using PHP and Cloudant)

Is it possible to retrieve a document, based on an attribute of that document?

I want to be able to test my users on sign up if the email already exists or not? It seems to me however, that you can only retrieve documents by _id...

I am using Cloudant as a cloud-service which uses CouchDB.

Upvotes: 0

Views: 1368

Answers (1)

Marcin Skórzewski
Marcin Skórzewski

Reputation: 2854

You can use the e-mail address as an id of the document, so no other document with the same e-mail can be added. You can also use the essential feature of the CouchDB, the view, to check if e-mail exists before insertion. Both methods require later conflict resolution. If first case, there may be another Couch node with conflicting document that has yet to be replicated. In second case, two users may add the accounts to the same server, but both will first check for existing e-mails, and then both will add their accounts.

Adding view requires adding the design document where the definition of calculated view is. You can create an index with the map function like this:

function (doc) {
  if (!doc.email) return;
  emit(doc.email, doc);
}

You can query the view with:

http://localhost:5984/YOUR_DTABASE/_design/YOUR_DESIGN_DOCUMENT/_view/YOUR_VIEW?key='[email protected]'

Note, that e-mail comparison is not that trivial as you could expect:

  1. DNS domain name (after "@") is case insensitive (user name is usually case sensitive)
  2. In typical e-mail system you can assign aliases.
  3. Some e-mail systems allow to embed destination folders and additional information that changes the e-mail string but directs to the same box (e.g. [email protected]).
  4. Gmail ignores ".", so [email protected] equals [email protected]

Upvotes: 2

Related Questions