Delete Document in PouchDB

Delete Document

To delete a PouchDB document the db.remove() method is used.

Syntax:

db.remove( doc_Id, doc_Rev, [callback] )

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 “DeleteDocument.js” within a folder named “Examples”.
  • Add the below code to the file. DeleteDocument.js:

    var PouchDB = require('PouchDB');
    var db = new PouchDB('Example_Database');
    db.remove('100', '1-99a7a70ec2a34678845637a16d57344f', function(err) {
    if (err) {
    return console.log(err);
    } else {
    console.log("Document Successfully Deleted.");
    }
    });
  • Open the command prompt.
  • Execute the .js file.
    node DeleteDocument.js
    

    Console Output:

    Document Successfully Deleted.
    
  • Explanation: The values in the document with ID “100” present in the “Example_Database” is deleted and thus the document.  

    Verification:

    On retrieving a deleted document, it will show a Not Found message, along with the status, error, reason and document ID.

    Output:

    {  [not_found: missing]
    status: 404,
    name: ‘not_found’,
    message: ‘missing’,
    error: true,
    reason: ‘deleted’,
    docID:100}

    To delete a Document from Remote Database:

    Instead of the database name, pass the path of the database to delete a document from 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 “DeleteRemoteDocument.js” within a folder named “Examples”.
    • Add the below code to the file. DeleteRemoteDocument.js:

      var PouchDB = require('PouchDB');
      var db = new PouchDB('http://localhost:5984/students');
      db.remove('100', '3-897c876543ad71f53b345feda12e65b1', function(err) {
      if (err) {
      return console.log(err);
      } else {
      console.log("Document Successfully Deleted.");
      }
      });
    • Open the command prompt.
    • Execute the .js file.
      node DeleteRemoteDocument.js

    Explanation: The document with ID “100” present in the “students” database in CouchDB is deleted from the database through PouchDB.

    Verification:

    Check CouchDB server for the deleted document.

    Please follow and like us:
    Content Protection by DMCA.com