PouchDB query using parameters-open source projects pouchdb/pouchdb

chesles

Your map function loses its closure because it is re-evaluated inside of PouchDB (that’s how it gets the emit function). This means you can’t access any variables from your code, but you can still query the database.

In PouchDB, views are not persistent, so your query always looks at every document in the database, and you have to do the filtering after the map function. Something like this:

function findCars(horsePower, callback) {
  // emit car documents
  function map(doc) {
    if(doc.type == 'car' && doc.value) {
      emit(doc.value, null);
    }
  }

  // filter results
  function filter(err, response) {
    if (err) return callback(err);

    var matches = [];
    response.rows.forEach(function(car) {
      if (car.hp == horsePower) {
        matches.push(car);
      }
    });
    callback(null, matches);
  }

  // kick off the PouchDB query with the map & filter functions above
  db.query({map: map}, {reduce: false}, filter)
}

Is one way to solve this problem. Pouch will iterate over each document, passing it to your map function. When done, filter gets called with an array of all the emitted documents. filter does not lose its closure context, so you can filter the results based on horsepower or any other field here.