Hi Steve,
I'm kind of confused about how you get access to the `db` in the
first place in your example. I'm going to assume something like:
var db = null;
/* Initialize the database */
var initial_records = [ /* your data here */ ];
PouchDB.destroy('vehicles')
.then(function() {
db = new PouchDB('vehicles');
return db.bulkDocs(initial_records);
})
.then(database_is_ready());
What I mean is that you need to make sure the database is initialized
before you start using it, which can only happen for sure in a `.then`
after your `bulkDocs` command.
Also notice how I `return` the Promise that `db.bulkDocs` generates -- this
ensures sequentiality.
/* Use the database */
function database_is_ready() {
// main body for the application... at some point:
var user_selected_drive = get_user_selected_drive();
findDrive(user_selected_drive)
.then(showDrive);
});
Notice how I use `.then` here again; this means that our `findDrive()`
will need to return a Promise. (More on this later.)
This is the map function:
function by_drive(doc) {
emit(doc.drive, null);
}
You'll notice that the map emits for all documents; the key of the index
is the `drive` field. Then in `db.query` we simply ask for that key,
there's no need to do an additional comparison in the display function.
The other thing is that you need to add `include_docs` if you want to
see any documents in the results.
Then for your `map` to be meaningful you're probably looking into
something which actually provides `doc` and `map` variables (I don't see
how they would get populated in your example) and uses the `drive`
variable provided to the `findDrive()` function.
function findDrive(drive) {
return db.query({map: by_drive}, {key: drive, include_doc:true})
.then(function (response) {
return response.rows.map(function(row){return row.doc});
});
}
Notice how `findDrive()` returns the Promise created by `db.query`.
Finally here's the display function:
function showDrive(matches) {
matches.forEach(function(row) {
document.getElementById('display').innerHTML +=
row.doc.drive + ', ' + // etc.
}
It's essentially identical to the one you showed minus the array-building.
You'll also notice I didn't check for errors. If you want to do that,
a good place to do that would be in a
.catch(function(error){...})
right after the line that says `.then(showDrive)` in `database_is_ready`.
I haven't tested any of this code so don't assume it'll work out of the
box, but HTH.
S.
--
tel:
+33643482771
http://stephane.shimaore.net/