Search code examples
viewcouchdbchange-notification

Couchdb get the changed document with each change notification


I'm quite sure that I want to be notified with the inserted document by each insertion in the couch db.

something like this:

http://localhost:5058/db-name/_chnages/_view/inserted-document

And I like the response to be something like the following:

{
   "id":"0552065465",
   "name":"james"
   .
   .
   .
}

Reconnecting to the database for giving the actual document by each notification can cause performance issues.

Can I define a view that return the actual document by each change?


Solution

  • There are 3 possible way to define if a document was just added:

    1. You add a status field to your document with a specific status for new documents.
    2. If the revision starts with a 1- but it's not 100% accurate according to this if you do replication.
    3. In the changes response, check if the number of revision of the document is equal to one. If so, it means it was just added(best solution IMO)

    If you want to query the _changes endpoint and directly get the newly inserted documents, you can use the approach #1 and use a filter function that only returns documents with status="new".

    Otherwise, you should go with approach #3 and filter the _changes responses locally. Eg: your application would receive all changes and only handle documents with revisions array count equal to 1.

    And as you mentioned, you want to receive the document, not only the _id and the _rev. To do so, you can simply add the query parameter: include_docs=true