1
votes

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.

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
I figured as much. But how come the docs do not mention this. docs.couchdb.org/en/2.3.0/ddocs/ddocs.html#update-functions - bioffe
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
Last comment should be promoted to answer! - bioffe

1 Answers

2
votes

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"}