CouchDB: POST Data with Update Handler

837 views
Skip to first unread message

Hank Knight

unread,
Nov 18, 2013, 9:04:31 AM11/18/13
to us...@couchdb.apache.org
I understand that I can pass information using an update handler like this:

http://127.0.0.1:5984/my_database/_design/my_designdoc/_update/in-place-query/mydocId?field=title&value=test

Is there a way to use POST data with an update handler?

I would like to post this data:
{
"hello": "world",
"x": 123
}

through an update handler.

Thanks.

Dave Cottlehuber

unread,
Nov 18, 2013, 9:14:42 AM11/18/13
to us...@couchdb.apache.org, Hank Knight
Yes.

http://wiki.apache.org/couchdb/Working_with_Forms
https://couchdb.readthedocs.org/en/latest/couchapp/ddocs.html#update-functions

Note for POST you can’t use the docname, for that use PUT instead.

--
Dave Cottlehuber
Sent with Airmail(http://airmailapp.com/tracking)

Robert Newson

unread,
Nov 18, 2013, 9:15:59 AM11/18/13
to us...@couchdb.apache.org
See https://wiki.apache.org/couchdb/Document_Update_Handlers#Request,
I think req.body is what you're after.

B.

Mike Marino

unread,
Nov 18, 2013, 9:17:07 AM11/18/13
to us...@couchdb.apache.org
On Mon, Nov 18, 2013 at 3:04 PM, Hank Knight <hknig...@gmail.com> wrote:
> I understand that I can pass information using an update handler like this:
>
> http://127.0.0.1:5984/my_database/_design/my_designdoc/_update/in-place-query/mydocId?field=title&value=test
>
> Is there a way to use POST data with an update handler?

Yes, you leave out the docid as in
http://wiki.apache.org/couchdb/Document_Update_Handlers and include
your data in the body of the request, if you want to use this to
generate a new document. See, e.g.

https://github.com/mgmarino/nEDM-Interface/blob/master/_default/lib/updates.js

For an example of pulling all the data into the new document. (It
uses the req.uuid as the new doc's _id, which may or may not be good
for your case.)

Hank Knight

unread,
Nov 18, 2013, 10:53:13 AM11/18/13
to us...@couchdb.apache.org
The problem is that the data passed via POST that is accessed with
req.body is being added in a single string.


This is what I get:
"data": "{\"hello\": \"world\", \"number\": 23}"


But I want this:
"data": "{
"hello": "world",
"number": 23
}


Here is my update function:

{
"_id": "_design/time2id",
"updates": {
"u": "function (doc, req) {var doc = new Object();doc._id =
String(Math.round(new Date().getTime()/1000));doc.data=req.body;return
[doc, \"Done\"];}"
}
}

I call it like this:

curl -k -u "uiim...@sharklasers.com:password123" -X PUT
https://zuhqtr5.couchappy.com/testupdates/_design/time2id/_update/u/
-d '{"hello": "world", "number": 23}' -H "Content-Type:
application/json"

Mike Marino

unread,
Nov 18, 2013, 10:55:27 AM11/18/13
to us...@couchdb.apache.org
Try JSON.parse as in the example I sent earlier.
Reply all
Reply to author
Forward
0 new messages