Question

I'm using nodejs with the module cradle to interact with the couchdb server, the question is to let me understanding the reduce process to improve the view query...

For example, I should get the user data from his ID with a view like this:

map: function (doc) { emit(null, doc); }

And in node.js (with cradle):

db.view('users/getUserByID', function (err, resp) {
  var found = false;

  resp.forEach(function (key, row, id) {
      if (id == userID) {
        found = true;
        userData = row;
      }
  });

  if (found) {
     //good, works
  }
});

As you can see, this is really bad for large amount of documents (users in the database), so I need to improve this view with a reduce but I don't know how because I don't understand of reduce works.. thank you

Was it helpful?

Solution

First of all, you're doing views wrong. View are indexes at first place and you shouldn't use them for full-scan operations - that's ineffective and wrong. Use power of Btree index with key, startkey and endkey query parameters and emit field you like to search for as key value.

In second, your example could be easily transformed to:

db.get(userID, function(err, body) {
    if (!err) {
      // found!
    }
});

Since in your loop you're checking row's document id with your userID value. There is no need for that loop - you may request document by his ID directly.

In third, if your userID value isn't matches document's ID, your view should be:

function (doc) { emit(doc.userID, null); }

and your code will be looks like:

db.view('users/getUserByID', {key: userID}, function (err, resp) {
    if (!err) {
      // found!
    }
});

Simple. Effective. Fast. If you need matched doc, use include_docs: true query parameter to fetch it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top