1

I am trying create an equivalent of create/update trigger used in traditional RDBMs. create_ts is being created fine, however update_ts part is not working for me.

"updates": {
  "add_ts": "function(doc, req)
               { if(!doc){
                   var result=JSON.parse(req.body);
                   result.created_ts=new Date();
                   return [result, 'Created']
               }
              doc.update_ts=new Date(); 
              return [doc,'Updated'];  
              }"
},

The document creates all right:

curl -X POST $COUCHDB_URL/mobile_gateway/_design/devicetokens/_update/add_ts  -d ' {"_id":"aaaa", "boris":"Ioffe"} '

   {
   "_id": "aaaa",
   "_rev": "7-70069ed48a5fa2a571b5ad83067010b9",
   "boris": "Ioffe",
   "created_ts": "2018-12-24T20:24:58.064Z"
   }

curl -X PUT $COUCHDB_URL/mobile_gateway/_design/devicetokens/_update/add_ts  -d ' {"_id":"aaaa", "boris":"Loffe"} '

{"error":"conflict","reason":"Document update conflict."}

I feel I am missing something fundamental in my understanding couchdb document updates.

bioffe
  • 6,283
  • 3
  • 50
  • 65
  • 1
    When updating a document, you must also include the revision. Otherwise it attempts to create it, and finds that it already exists. – Hypnic Jerk Dec 26 '18 at 18:23
  • I figured as much. But how come the docs do not mention this. https://docs.couchdb.org/en/2.3.0/ddocs/ddocs.html#update-functions – bioffe Dec 26 '18 at 20:51
  • 1
    `When the request to an update handler includes a document ID in the URL, the server will provide the function with the most recent version of that document.` Based on this sentence it seems that you have left off the id in the url in the `PUT` and have only provided the body. – Hypnic Jerk Dec 26 '18 at 20:58
  • Last comment should be promoted to answer! – bioffe Dec 27 '18 at 21:51

1 Answers1

2

Moving comment to answer based on OP request.

When the request to an update handler includes a document ID in the URL, the server will provide the function with the most recent version of that document. Based on this sentence at the beginning of the second paragraph, it seems that you have left off the id in the url in the PUT and have only provided the body.

Your request should look something like this

curl -X PUT $COUCHDB_URL/mobile_gateway/_design/devicetokens/_update/add_ts/aaaa  -d ' {"_id":"aaaa", "boris":"Loffe"}
Hypnic Jerk
  • 1,192
  • 3
  • 14
  • 32