Posted under CouchDB
Permalink
Tags Bug, CouchDB, Gotcha, Tip
I had a bug whereby my view was emitting the same place document twice. This was strange as the database clearly did not contain 2 copies of the document. I had seen what appeared to be a similar issue before bud at the time did not track down the cause.
It turned out to be a bug in the view definition. The original (buggy) version follows:-
function (doc) {
if (doc.type == ‘place’) {
emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 0], null);
emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 1], {_id: doc.placeFeaturesId});
}
}
The problem with this is that when doc.placeFeaturesId is null/undefined, the second emit emits its key plus an “_id” with an undefined/null value in the generated json. The result of this is that when using ?include_docs=true to include the documents, CouchDB applies a default behaviour due to the null, and emits the place document again a second time. The following fix prevents the second emit when there are no placeFeatures present, which prevents the place document being emitted a second time. This solves the problem:-
function (doc) {
if (doc.type == ‘place’) {
emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 0], null);
if (doc.placeFeaturesId) {
emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 1], {_id: doc.placeFeaturesId});
}
}
}
The lesson here is to be careful to handle undefined or null values in the view code when emitting entries in a view definition as this can cause strange behaviour such as the duplicates above.