Click anywhere to close

One-to-Many Relationships in CouchDB

Recently I have been playing around a lot with CouchDB, and one of the more challenging aspects of it is understanding the map/reduce functions on views.

This is how I handle a One-to-Many foreign key between different types of objects.

The data is set up as follows:
{
    "_id":1,
    "type":"person",
    "name":"mike"
    ...
},
{
    "_id":2,
    "type":"pet",
    "name":"barky",
    "owner":1
    ...
},
{
    "_id":3,
    "type":"pet",
    "name":"chirpy",
    "owner":1
    ...
}
And here is the map/reduce function that I use to retrieve a person and their pets:
Map:
function( doc ) {
    if( doc.type === "person" )
        emit( [doc._id, 0], doc );
    if( doc.type === "pet" )
        emit( [owner, 1], doc );
}
Reduce:
function( keys, values ) {
    var person = { _id: null, pets: [] }
    for( var value in values ) {
        var cur = values[ value ];
        if( cur.type === "user" ) {
            person._id = cur._id;
        }
        if( cur.type === "pet" ) {
            person.pets.push( cur );
        }
    }
    return person;
}

Now just make sure that you query your view with a group_level of 1, and it should return to you a user object with an array pets.


Recent Posts

Shirtbot It's a slack bot that makes shirts
Posted: August 01, 2021
I feel stuck in the the engineering for engineers trap If you aren't an engineer please read this and reach out, I'd love to chat
Posted: June 20, 2021
Unwritten Coding Standards: Function Ordering A standard for how you should order functions in files to increase the consistency of your code bases
Posted: May 15, 2021
Designing a guitar with hot-swappable pickups I made a custom guitar with hot-swappable pickups
Posted: May 02, 2021
How to design a motherboard for your electronics project - Part 2 Designing a motherboard for your project is a great second step when developing an electronics project. This is the guide I wish existed when I got started doing this.
Posted: April 25, 2021