Hello.
Following a popular example, say I have tow classes of documents in my
database, posts and comments:
{ id:'post-1', type:'post', subject:'first post', body:'...'}
{ id:'post-1-comment-1', type:'comment', post:'post-1' , body:'first comment'}
{ id:'post-1-comment-2', type:'comment', post:'post-2' , body:'second comment'}
{ id:'post-2', type:'post', subject:'second post', body:'...'}
{ id:'post-2-comment-1', type:'comment', post:'post-1' , body:'first comment'}
I'd like to have view with all posts and a count of comments.
{ id:'post-1', type:'post', subject:'first post', body:'...', comments:2}
{ id:'post-2', type:'post', subject:'secong post', body:'...', comments:1}
I was able to obtain what I wanted with a list function, but I was
hoping to do it using only a view.
I've tried with the map/reduce below, but I get the reduce_overflow error
// map.js
function(doc) {
if (doc.type == "post") {
map([doc._id, 0], doc);
} else if (doc.type == "comment") {
map([doc.post, 1], doc);
}
}
// reduce.js
function(keys, values, rereduce) {
log('>>>>>>');
log('>>>>>>');
var result = {};
if (!rereduce) {
values.forEach(function(doc) {
log({doc:doc});
// this is a question
if (doc.type == "post" ) {
if (result[doc._id])
result[doc._id].subject = doc.subject;
else
result[doc._id] = { subject:
doc.subject };
}
else if (doc.type == "comment") {
if (!result[doc.post])
result[doc.post] = { comments: 0 };
result[doc.post].comments++;
}
});
}
else {
values.forEach(function(value) {
for (var post_id in value) {
if (!result[post_id]) result[post_id] = {
subject: '', comments: 0 }
if (value[post_id].subject) {
result[post_id] =
value[post_id].subject;
}
if (value[post_id].comments) {
result[post_id].comments +=
value[post_id].comments
}
}
});
}
log("<<<<<<");
log("<<<<<<");
return result;
}
thanks
--
:Matteo Caprari
[email protected]