1

How are people adding extra fields via the update handler in Couchdb ? I'd like to add the author ( I have a validation function to check the user is logged in) and the id added when a new documenter is created via an update handler.

The authors name is coming from req.userCtx.Name, the data I've sent is in req.body and I'm using the req.uuid as the _id

"updates": {
   "new": "function(doc,req) { var message = req.uuid; return [ { _id : req.uuid, "author" : req.userCtx.name, data : req.body}, message]}"
}

Data been sent via a curl POST

$ cat test.json
{"data" : {"name" : "myname","dob" : "myDOB"}}

This is how the data looks via the update handler

{"_id":"a018fed749d64f5db754b39af803a88f","_rev":"1-939793c36d2bfe4de86f808fab056959","author":"admin","data":"{\"name\" : \"myname\",\"dob\" : \"myDOB\"}"}

If I do a standard POST ( not via an update handler ) it looks like this ..

{"_id":"a018fed749d64f5db754b39af803b621","_rev":"1-e44f0471e1df1018439fee3681b49547","data":{"name":"myname","dob":"myDOB"}}

What am I doing wrong ?


EDIT

Typical having spent a few hours looking and then posting the qestions I find the solution.

This helped - http://grokbase.com/t/couchdb/user/10cbesx3zz/how-should-i-handle-json-parsing-in-update-handler

{ "new": "function(doc,req) { var data = JSON.parse(req.body); data['_id'] = req.uuid;data.author = req.userCtx.name; message = req.uuid; return [ data, message]}" }

doc now has id and author ..

{"_id":"a018fed749d64f5db754b39af80406b7","_rev":"1-c486b02d6f320eb15e6115e71b3f02cc","data":{"name":"myname","dob":"myDOB"},"author":"admin"}
Rob W
  • 341,306
  • 83
  • 791
  • 678
Adam
  • 55
  • 6
  • As I new user it takes 8 hours before I can answer your own question so instead of never answering thought I'd edit in case I forgot to come back. Have now answered :-) – Adam Jul 31 '12 at 20:34

2 Answers2

1

Typical having spent a few hours looking and then posting the qestions I find the solution.

this from - http://grokbase.com/t/couchdb/user/10cbesx3zz/how-should-i-handle-json-parsing-in-update-handler

{
   "new": "function(doc,req) { 
        var data = **JSON.parse(req.body)**; 
        data['_id'] = req.uuid;data.author = req.userCtx.name; 
        message = req.uuid; 
        return [ data, message]
    }"
}

doc now has id and author ..

{   "_id":"a018fed749d64f5db754b39af80406b7",
    "_rev":"1-c486b02d6f320eb15e6115e71b3f02cc",
    "data":{"name":"myname","dob":"myDOB"},
    "author":"admin"
}
GDP
  • 8,109
  • 6
  • 45
  • 82
Adam
  • 55
  • 6
1

It could help you to make your Update Handler function return your Request object like this code:

(...)
return [doc, JSON.stringify(req)]
(...)

I did that to understand/identify what were the properties coming in the Request object (here is the Request object Documentation: http://docs.couchdb.org/en/latest/json-structure.html#request-object)

Hamad
  • 5,096
  • 13
  • 37
  • 65
joaquindev
  • 143
  • 1
  • 5