0

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?

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.