Search code examples
phpcurlcouchdbcloudant

CouchDB view to find users via case-insensitive email


I have a CouchDB view in my _user database, where I can find users based on their email addresses (user.email is part of their user doc).

{
  "_id": "_design/find-user",
  "views": {
    "email->doc": {
      "map": "function (doc) {\n  emit(doc.email, doc);\n}"
    }
  },
  "language": "javascript"
}

I am using the following curl url via PHP to access matching users:

curl_setopt($ch, CURLOPT_URL, $url . '/_users/_design/find-user/_view/email->doc?key="' . $email . '"');

This works, but is case sensitive, which I don't want. For example, I need $email = TesT@example.com to find tESt@example.com in my database.

I have tried the following, but that only transforms the output.

function (doc) {
  emit(doc.email.toLowerCase(), doc);
}

Solution

  • You're on the right track with toLowerCase(). The only piece you're missing is that you must also transform your search term.

    Don't search for "TEST@example.com", instead search for strtolower("TEST@example.com"):

    curl_setopt($ch, CURLOPT_URL, $url . '/_users/_design/find-user/_view/email->doc?key="' . strtolower($email) . '"');