Couchdb using nano , how to write search query

3.4k Views Asked by At

I am facing problem using couchdb. I am using nano module for this in nodejs. How can I implement search like match for user name and password. I tried this

body.rows.forEach(function(row) {
  if(row.doc._id==user_id && row.doc.password==password){
    found = true;
    data = row;
  }
});

but this is slow process

2

There are 2 best solutions below

0
On

Your code body.rows.forEach ... is a map function (it iterates over every row) which executes a filter function if(row.doc._id==user_id ... to a row. Thats what CouchDB views do - exactly the same.

but this is slow process

True. Because of that CouchDB creates an index (a B-Tree that is a file inside CouchDB's database directory) and keeps this index up-to-date. The performance advantage for every request is that the result will be taken from the already prepared index instead of a just-in-time calculation as in your example.

The CouchDB view map function could look like:

function(doc) {
  emit([doc._id,doc.password], null)
}

The key of every row is [:username,:password] and the value is null. If you request

/:db/:ddoc/_view/:name?key=[":username",":password"]

you will get the row immediately. Append a &include_docs=true and you will also get the whole doc appended to the row (alternatively you could emit a partial of the doc as value instead of null)

handling user accounts in CouchDB

User accounts and especially passwords are confidential data. CouchDB has the built-in _users db for it. I will not go into the details of the access control specifics of that db but want to say Store user account data there!. If you need account data outside this db then interpret that docs as "public profiles" e.g. to let users discover and connect to each other.

1
On

I found solution for search using key value in couch db using nano.

First you have to create design document and view (and implement logic in that) then use them.

exports.testwhere = function (req, res) {
   var db = nano.use('ionic');
   db.insert({
      "views": {
         "by_email_and_password": {
            "map": function (doc) {
               emit([doc.email, doc.password], doc);
            }
         }
      }
   }, '_design/users', function (error, response) {
      console.log("yay");
   });
}


exports.testsearch = function (req, res) {
   var db =
      nano.use('ionic');
   db.view('users', 'by_email_and_password', {
      key: ["[email protected]", "aaa123"], include_docs: true
   }, function (err, res) {
      if (!err) {
         console.log("Result " + JSON.stringify(res));
      }
      else {
         console.log(err);
      }
   });
}