Question

I have a couple of documents in my couchdb database which all are like:

{
"_id":"1234567890",
"name": [
  "category1": 5,
  "category2": 8
]
}

I want to have a map function which gives me "category1" as key and 5 as value. I just can't separate "category" and 5.

I tried the following:

function(doc){
    if(doc.name){
        doc.name.forEach(function(sth) {
            emit(sth, null); 
        });
    }
}

Maybe someone can help me find a solution?

Was it helpful?

Solution

Mind that:

  • CouchDB function emit() takes two parameters, first is a key (eg. "category1"), second is a value (eg. 5). See the view API documented in the CouchDB wiki.
  • [key:val, ...] is not correct JSON field syntax, did you mean list of single field records ([{"key1": val1}, {"key2": val2}, ...]) or single multi-field record ({"key1": val1, "key2": val2, ...})?
  • In case of "name": [{ "category1": 5}, {"category2": 8 }] argument of forEach continuation is {"category1": 5}, and you should get somehow "category1" and 5 separately (forEach() or for (var key in sth) {} once more??).
  • In case of "name": { "category1": 5, "category2": 8 }, remember the JS object ({"field": val, ...}) does not have forEach method, array ([val1, val2, ...]) prototype does.

Assuming you meant "name": { "category1": 5, "category2": 8 } as the name, consider trying the following map:

function (data) {
  if (date.name) {
    for (var sth in name) {
      emit(sth, name[sth]);
    }
  }
}

If you are JavaScript beginer, try writing proper code in console first. You can use the one found in the web-browser (Firefox, Chrome have build-in, I advise FireBug addon for Firefox). Good luck!

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