PouchDB Intro

PouchDB

What if you could add a database to your website (or mobile app), without the hassle of server infrastructure? What if you’re pretty well versed in JavaScript and wish to put those skills to good use? That’s where this new library comes to the rescue. Check out our PouchDB Intro to get started with a cool, easy database solution.

PouchDB is touted as an open-source JavaScript library that gives you the ability to do all the database operations you need: create/destroy databases; create/modify documents; retrieve/display data. Best of all, it runs right in the browser, only needs one JavaScript library, and uses syntax you already know.

PouchDB Setup

For our tutorial you’ll need your favorite code editor, and a web browser—that’s it. You can run our live version of the project to see how it should work (don’t forget to open your Developer Tools Console!), and you can get a copy of the source code at GitHub. We’re going to write HTML, JavaScript/jQuery, and PouchDB code. It’s up to you style with CSS and add extra features (like error-handling).

Foundational Elements

Create a basic HTML5-compliant document, the input fields and buttons, the placeholder to show results/feedback, and links to our libraries

<!doctype html>
<html>
 <head>
   <meta charset="utf-8">
   <title>PouchDB Intro</title>
 </head>
 <body>
   <h1>PouchDB Intro</h1>
   <form id="formUser">
     <p><label for="inputLast">Last Name </label><input type="text" placeholder="Campos" name="inputLast" id="inputLast"> </p>
     <p><label for="inputFirst">First Name: </label><input type="text" placeholder="Victor" name="inputFirst" id="inputFirst"></p>
     <p><label for="inputUID">Username: </label><input type="text" placeholder="vcampos" name="inputUID" id="inputUID"> </p>
     <input type="button" value="Save Name" id="btnAddNames">
     <input type="reset" value="Clear fields">
     <input type="button" value="Show Names" id="btnShowNames">
   </form>
   <div id="divResults"></div>
 <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 <script src="https://github.com/pouchdb/pouchdb/releases/download/5.4.5/pouchdb-5.4.5.min.js"></script>
 <script>

 </script>
</body>
</html>

Initialize the database

PouchDB allows us to use all the standard database operations; we do so by creating a new object of type PouchDB. Let’s wrap it in a function so we can create the database whenever we want (say, after deleting it to start over). Place the following in the empty <script> block.

 var db;
 function initDB() {
    db = new PouchDB("savedUsers");

    db.info(function(error, result) {
    if(!error) {
      console.log(result);
    } else {
      console.log(error);
    }
   });

   return db;
 }
 
 initDB();

Input a name and clear fields

We’ll set up an event handler to take the user’s input, bundle it in JSON format (a Document), and then .put() it into the database. Then we’ll either display the data on-screen (that function comes a little later), or return an error message. Lastly, we’ll need to clear the fields to accept new input. Notice that what we add to PouchDB is a string in JSON format, and it must have a unique _id, the Primary Key. We will need it to retrieve and edit Documents.

$("#btnAddNames").on("click", addUsers);
 function addUsers() { 
   var uLast = $("#inputLast").val(),
   uFirst = $("#inputFirst").val(),
   uUID = $("#inputUID").val();
 
 var aUser = {
   "_id" : uLast,
   "nameFirst" : uFirst,
   "nameUID" : uUID
 };
 
 db.put(aUser, function(error, result) {
    if(!error) {
     $("#divResults").html("<p>Saved!</p>");
     showUsers();
     console.log(result);
     clearFields();
    } else {
     $("#divResults").html("<p>&iexcl;Error!</p>");
     console.log(error);
    }
   });
 }
 
 function clearFields() {
   $("#formUser")[0].reset();
 }

Display the names

Once names are added to the database as Documents, we’ll need to retrieve them and display them to the user. We first need to get all the names via .allDocs(), sorted alphabetically. Then we’ll build a nice table to display the names in our waiting <div>. We’ll add more elements to str to be able to delete and modify names afterward.

$("#btnShowNames").on("click", showUsers);
 function showUsers() {
   db.allDocs({"include_docs" : true, "ascending" : true}, function(error, result) {
     showTableOfUsers(result.rows);
   });
 }
 
 function showTableOfUsers(data) {
   var str = "<p><table border='1' id='userTable'>";
   str += "<tr><th>Last Name</th><th>First Name</th><th>UID</th><th>&nbsp;</th></tr>";
   
  for(var i = 0; i < data.length; i++) {
   str += "<tr><td>" + data[i].id + 
   "</td><td>" + data[i].doc.nameFirst + 
   "</td><td>" + data[i].doc.nameUID +
   "</td><td class='editPencil'>&#x270E;" +
   "</td></tr>";
  }
 
 str += "</table></p>";
 
 $("#divResults").html(str);
 }

Delete a name

Every name added to the database is in a JSON-formatted “bundle” that we can reference via its unique _id. So we’ll have the user input a Last Name in order to delete a Document (a bundle of user data). So, first, to showTableOfUsers(data), add the following before $(“#divResults”).html(str);

str += "<hr>"; 
str += "<input type='text' placeholder='Lastname' id='inputDeleteName'><button id='btnDeleteNames'>Delete Name</button>";

Then, after the showTableOfUsers(data) function, create the following new function to take the input last name and delete the user from the database.

 $("body").on("click", "#btnDeleteNames", deleteUsers);
 function deleteUsers() {
   var theUser = $("#inputDeleteName").val();

   db.get(theUser, function(error, result) {
     db.remove(result, function(error, result) {
     if(result) {
       console.log(result);
       showUsers();
      } else {
       console.log(error);
       $("#inputDeleteName").val("");
       alert("The user '" + theUser + "' does not exist!");
      }
     });
  });
 }

Update a name

If we need to update a name, we need to supply PouchDB a valid _id and the changes. We’ll first create some new input fields to take the new values. Add the following to the showTableOfUsers(data) function, before $(“#divResults”).html(str);

str += "<hr>"; 
str += "<button id='btnUpdateName'>Update Name</button><br><input type='text' placeholder='Last Name' id='updateLName'><br><input type='text' placeholder='First Name' id='updateFName'><br><input type='text' placeholder='Username' id='updateUID'>";

Then we’ll create a function to take the new data and replace the old data in Pouch. Recall that, when we built our table to display the names, we added a column with an Edit Pencil icon to auto-populate these fields. Our first function sets this up. Our second function updates the database. Notice that our new .put() requires the _rev key. This is what allows PouchDB to deal with collisions in data.

$("#divResults").on("click", ".editPencil", function() { updateNamePrep($(this).parent()) });
 function updateNamePrep(thisObj) {
   var tmpLName = thisObj.find("td:eq(0)").text(),
   tmpFName = thisObj.find("td:eq(1)").text(),
   tmpUID = thisObj.find("td:eq(2)").text();

   $("#updateLName").val(tmpLName);
   $("#updateFName").val(tmpFName);
   $("#updateUID").val(tmpUID);
}
 
$("body").on("click", "#btnUpdateName", updateName);
function updateName() {
 var newLName = $("#updateLName").val(),
 newFName = $("#updateFName").val(),
 newUID = $("#updateUID").val();
 
 db.get(newLName, function(error, result) {
   if(error) {
     console.log(error);
     $("#updateLName").val(""),
     $("#updateFName").val(""),
     $("#updateUID").val("");
     alert("The user '" + newLName + "' does not exist!");
   } else {
   console.log(result);
   db.put({
     "_id" : newLName,
     "nameFirst" : newFName,
     "nameUID" : newUID,
     "_rev" : result._rev
   }, function(error, result) { showUsers()} );
  }
 });
}

Delete the database

If we need to clear all the data in Pouch, we have a way to do it, of course. Let’s add the trigger button to the showTableOfUsers(data) function, again, before $(“#divResults”).html(str);

str += "<hr><hr>"; 
str += "<button id='btnDeleteDB'>Delete DB</button>";

And then we’ll write the function to .destroy() the database, with a bit of confirmation, of course. It would be up to you to make it more safe (perhaps adding stronger confirmation-checking).

$("body").on("click", "#btnDeleteDB", function() { deleteDB() });
function deleteDB() {
 switch(confirm("Do you want to delete the Database?")) {
   case true:
      db.destroy(function(error, result) {
        if(error) {
        console.log(error);
      } else {
        console.log(result);
        initDB();
        showUsers();
      }
     });
     alert("Deleted!");
     break;
   case false:
     alert("Cancelled");
     break;
   default:
     alert("No DB to delete");
     break;
   }
}

Conclusion

When all the code is written, and we run it in the browser, we should see the fruits of our labor: a fully-functional database powered by JavaScript.

This, of course, is just an introduction to PouchDB. But it accomplishes several things: how to create a Database and how to delete it; how to add a Document to the Database, as well as how to delete and modify it; and, of course, how to display your data on screen. Remember to check the live version of the project, or download the source code. PouchDB works on a website, as well as a mobile app (via Cordova, for example). If this works for you, share your experiences and help the community grow!

Challenge yourself:


Reply?

Copyright © 2016 VmC Ink.