How to update a pouch db document through Angular?

I start this post assuming you know how to integrate pouch db with angular .

If not please refer this post : (How to integrate pouch db with angular?)

Once pouch db is integrated you might want to update documents into pouch db through Angular .

Here is how to do it:

Step 1: Retrieve the record to be updated

First fetch the record from Pouch DB .

Please refer this post on how to do it ( How to search documents in Pouch DB)

Step 2: Prepare a pouch db document with the updated values and the same identifier

For example here is a document I got from Pouch DB which has two fields ‘name’ and ’emailid’ apart from the identifier ‘_id’ which I passed while saving the document:

I am entering new values in an angular template using reactive forms and preparing the document in component using the below typescript code:

   var pouchform = {

      _id: this.result[0]._id,
      name: this.pouchform.value.newName,
      emailid: this.pouchform.value.newEmail

    }

Step 3: Call pouch db ‘put’ method

Once the document is prepared I am calling ‘put’ API of Pouch DB.

The same API is used for both saving and updating documents.

Here is the typescript code:

  update(){

    

    var pouchform = {

      _id: this.result[0]._id,
      name: this.pouchform.value.newName,
      emailid: this.pouchform.value.newEmail

    }

    
    this.pouchdb.put(pouchform, function (result, error) {

      console.log(result);

      if (!error) {

        alert("Pouch form updated successfully")
      }
    });
  }

I assumed that things will work fine and clicked on ‘update’ button in my template.

And then this happened:

Pouch DB threw an error :

Ahh!After some analysis I found out the root cause.

Pouch DB requires the revision number of the document to be updated!

I passed the same as below:

update(){

    

    var pouchform = {

      _id: this.result[0]._id,
      _rev: this.result[0]._rev,
      name: this.pouchform.value.newName,
      emailid: this.pouchform.value.newEmail

    }

    
    this.pouchdb.put(pouchform, function (result, error) {

      console.log(result);

      if (!error) {

        alert("Pouch form updated successfully")
      }
    });
  }

And voila ! the document got updated.

Here is the Github repository URL with the sample code :

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

Thumb rule : Always use revision number to update any pouch db document!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s