Skip to content

Instantly share code, notes, and snippets.

@daleharvey
Forked from nolanlawson/pouchdb_index_api.md
Created April 24, 2014 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daleharvey/11238052 to your computer and use it in GitHub Desktop.
Save daleharvey/11238052 to your computer and use it in GitHub Desktop.

PouchDB 2.3.0 index API proposal

Wherein we hack up our dream map/reduce API, slated to be introduced in PouchDB 2.3.0.

Basic

new PouchDB('mydb', {indexes: ['title']});

Creates the following design doc:

{
  _id: '_design/title',
  views: {
    'title': {
      map: function(doc) {
        var val = doc['title'];
        if (typeof val !== 'undefined' && val !== null) {
          emit(val);
        }
      }
    }
  }
}

Which you can query like this:

pouch.query('title', {key: 'Moonage Daydream'});

Emitting nulls/undefineds

new PouchDB('mydb', {indexes: [{name: 'title', nulls: true}]});

Builds up:

{
  _id: '_design/title',
  views: {
    'title': {
      map: function(doc) {
        emit(doc['title']);
      }
    }
  }
}

Complex keys

new PouchDB('mydb', {indexes: [{name: 'firstAndLastName', fields: ['firstName', 'lastName']}]);

Builds up:

{
  _id: '_design/firstAndLastName',
  views: {
    'firstAndLastName': {
      map: function(doc) {
        var fields = ['firstName', 'lastName'];
        var values = [];
        for (var i = 0; i < fields.length; i++) {
          var val = doc[fields[i]]);
          if (typeof val !== 'undefined' && val !== null) {
            values.push(val);
          } else {
            return;
          }  
        }
        emit(values);
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment