pouchdb
PouchDB is an open-source JavaScript database inspired by Apache CouchDB that is designed to run well within the browser.
1. setup and make database
1
npm install --save pouchdb
if browser only?
1
npm install --save pouchdb-browser
1
2
3
4
<script src="//cdn.jsdelivr.net/npm/pouchdb@8.0.1/dist/pouchdb.min.js"></script>
<script>
var db = new PouchDB('my_database');
</script>
2. include the module
1
2
var PouchDB = require('pouchdb');
var db = new PouchDB('my_database');
or,
1
2
var PouchDB = require('pouchdb-browser');
var db = new PouchDB('my_database');
3. create db and data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const db = new PouchDB('users');
const doc = {
_id: 'DaveInfo',
name: 'Dave',
age: 23,
occupation: 'designer'
};
db.put(doc).then((res) => {
console.log("Document inserted OK");
}).catch((err) => {
console.error(err);
});
4. read data
1
2
3
4
5
6
7
const db = new PouchDB('users');
db.get("PeterInfo").then((doc) => {
console.log(doc);
}).catch((err) => {
console.error(err);
});
5. update data
1
2
3
4
5
6
7
8
9
10
11
12
13
const db = new PouchDB('users');
db.get("PeterInfo").then((doc) => {
doc.occupation = "UX Designer";
doc.age = "103";
return db.put(doc);
}).then(() => {
return db.get("PeterInfo");
}).then((doc) => {
console.log(doc);
}).catch((err) => {
console.error(err);
});
6. delete data
1
2
3
4
5
6
7
8
9
const db = new PouchDB('users');
db.get("PeterInfo").then((doc) => {
return db.remove(doc);
}).then((res) => {
console.log(`The document has been removed ${JSON.stringify(res)}`);
}).catch((err) => {
console.error(err);
});
This post is licensed under CC BY 4.0 by the author.