How to search documents in Pouch DB through Angular, based on specific field?

Photo by Skitterphoto on Pexels.com

Through Mango queries.

Pouch DB supports the feature of querying documents based on field values through a separate plugin and calls this feature as ‘Mango queries’. So the first step to avail this feature is to install it :

Assumption : you have already installed pouch db and able to save documents( Refer : https://fullstackdeveloper.guru/2020/03/21/how-to-integrate-pouch-db-with-angular/)

STEP 1:

Install pouch db find plugin:

npm install pouchdb-find

STEP 2:

In the angular component code import the Pouch DB plugin :

import PouchDBFind from 'node_modules/pouchdb-find';

STEP 3:

Initialize the plugin in the component constructor:

constructor(){
PouchDB.plugin(PouchDBFind);
}

STEP 4:

Create an index for the field based on which the documents are to be searched. (Eg) you want to retrieve all documents with a specific name)

 this.pouchdb.createIndex(
      {

        index: { fields: ['name'] }
      }
    );

STEP 5:

In the angular template call a method in component when user clicks on, say search button :

<form [formGroup]="pouchform">
<h2>Search By Name</h2>>

<label>Enter Name</label>
<input formControlName="searchName"/>
<br>
<button (click)="search()">Search</button>

<table>

  <tr *ngFor="let row of result">

    <td>{{row.name}}</td>
    <td>{{row.emailid}}</td>
  </tr>
</table>

</form>

STEP 6:

Use the below pouch db API in your component code :

this.pouchdb.find(

      {
        selector: {
          name: searchName
        }
      }
    )

Here ‘name’ is the field name and ‘searchName’ is the field value.

STEP 7:

The above method is an asynchronous call and it returns a ‘Promise’. To retrieve the result ‘await’ for the result and declare the component method as ‘async’ like below:

  async search() {



    let records = await this.getForms(this.pouchform.value.searchName);

    this.result = records.docs;


  }


  getForms(searchName) {


    return this.pouchdb.find(

      {
        selector: {
          name: searchName
        }
      }
    )

  }

Here ‘search()’ is the method called when the button is clicked in template . It is to be declared as async. The method getForms() makes the actual call to pouch db and its invocation is preceded by the keyword ‘await’.

The complete code is present in the below repository :

https://github.com/vijaysrj/pouchdb-angular/


Posted

in

, ,

by

Comments

One response to “How to search documents in Pouch DB through Angular, based on specific field?”

Leave a Reply to How to update a pouch db document through Angular? – The Full Stack DeveloperCancel reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading