The map function loses its closure because it is reevaluated inside PouchDB (the way it gets the emit function). This means that you cannot access any variables from your code, but you can still query the database.
In PouchDB, views are not permanent, so your query always looks at every document in the database, and you need to do filtering after the map function. Something like that:
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) }
This is one way to solve this problem. The cover will iterate over each document, passing it to the map function. When done, filter is called with an array of all emitted documents. filter does not lose the closing context, so you can filter the results based on power or any other field here.
source share