Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nolanlawson/11235281 to your computer and use it in GitHub Desktop.
Save nolanlawson/11235281 to your computer and use it in GitHub Desktop.
PouchDB 2.3.0 index API proposal

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);
      }
    }
  }
}

Conditions

new PouchDB('mydb', {indexes: [{name: 'firstName', require: ['type', 'person'}]);

Builds up:

{
  _id: '_design/firstName',
  views: {
    'firstAndLastName': {
      map: function(doc) {
        if (doc['type'] !== 'person') {
          return;
        }
        var val = doc['title'];
        if (typeof val !== 'undefined' && val !== null) {
          emit(val);
        }
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment