In this exercise we will have a look at PouchDB, which is a CouchDB clone written in JavaScript. It is a document-oriented database system. We'll mainly follow the PouchDB Getting Started Guide in this exercise.
-
Download this repository and install pouchdb in the package folder.
> npm install --save pouchdb
-
In index.js, use require to include pouchdb in your code.
var PouchDB = require('pouchdb');
-
Create a new PouchDB database to store to-dos.
var db = new PouchDB('todos');
-
Add a function to create a to-do to the database.
function addTodo(text) { var todo = { _id: new Date().toISOString(), title: text, completed: false }; db.put(todo, function callback(err, result) { if (!err) { console.log('Successfully posted a todo!'); } }); }
-
Add a function to retreive all the to-dos in the database and print them on the console.
function showTodos() { db.allDocs({include_docs: true, descending: true}, function(err, doc) { console.log(doc.rows); }); }
-
Add a function to update a to-do. For now the only update we'll allow is to have the to-do marked as completed.
function completeTodo(todo) { todo.completed = true; db.put(todo); }
-
Add a function to delete a to-do
function deleteTodo(todo) { db.remove(todo); }
-
Tell PouchDB to show us the to-dos on the console every time we change the database.
db.changes({ since: 'now', live: true }).on('change', showTodos);
-
Create three to-dos: "Clean dog", "Wash car", "Drink coffee".
addTodo("Clean dog"); ...
-
List all the todos.
showTodos();
-
Have showTodos store all of the to-dos in an array.
-
Update a to-do.
-
Delete a to-do.
-
Use express to create a todos HTTP API.