Update Document
The _rev or revision marker is used to update a document in PouchDB which is generated when a PouchDB document is created and is changed whenever a change or update is made to the document.
Example:
- Read the required document and get its _rev number.
Output:{ name: 'Tom', salary: 45000, experience: 3, _id: '100', _rev: '1-99a7a70ec2a34678845637a16d57344f' }
- Use the _rev to update the document.
- Create a file named “UpdateDocument.js” within a folder named “Examples”.
- Add the below code to the file.
UpdateDocument.js:
var PouchDB = require('PouchDB'); var db = new PouchDB('Example_Database'); doc = { salary: 50000, _id: '100', _rev: '1-99a7a70ec2a34678845637a16d57344f' } db.put(doc); db.get('100', function(err, doc) { if (err) { return console.log(err); } else { console.log(doc); } });
- Open the command prompt.
- Execute the .js file.
node UpdateDocument.js
Output:
{ salary: 50000, _id: '100', _rev: '2-c23478900ffg561ab723567g2be7865s' }
Explanation:
The values in the document with ID “100” present in the “Example_Database” is updated and thus the document.
Update a Document in Remote Database:
Instead of the database name, pass the path of the database to update a document in CouchDB or remote server.
Example:
- Read the required document and get its _rev number.
Output:{ _id: '100', _rev: '3-897c876543ad71f53b345feda12e65b1', name: 'Tom', salary: 45000, experience: 3 }
- Create a file named “UpdateRemoteDocument.js” within a folder named “Examples”.
- Add the below code to the file.
UpdateRemoteDocument.js:var PouchDB = require('PouchDB'); var db = new PouchDB('http://localhost:5984/students'); doc = { "_id": "100", "_rev": "3-897c876543ad71f53b345feda12e65b1", "name": "Jerry", "salary": 60000 } db.put(doc); db.get('100', function(err, doc) { if (err) { return console.log(err); } else { console.log(doc); } });
- Open the command prompt.
- Execute the .js file.
node UpdateRemoteDocument.js
Output:
{ _id: '100', _rev: '4-123agh3678975bc0d2314894dxzbab87', name: 'Jerry', salary: 60000 }
Explanation:
The values in the document with ID “100” present in the “students” database in CouchDB is updated with PouchDB.