User2427301
User2427301

Reputation: 23

CouchDB JSon response customization

I'm storing addresses data in Couchdb, and am looking for a way to get an array of just the values, instead of key: value for every record.

This is the current response:

{"total rows": 2438, "offset": 0, "rows":[
    {"id": "ec5de6de2cf7bcac9a2a2a76de5738e4", "key": "user_298774", "value": {"city": "Milano", "address":"Corso Como, 42b"},
    {"id": "a2a2a76de573ae4ec5de6de2cf7bcac9", "key": "user_276341", "value": {"city": "Vicenza", "address":"Via Quinto Sella, 118"}
    ... (etc).
]}

I only really need:

[{"city": "Milano", "address":"Corso Como, 42b"},
 {"city": "Vicenza", "address":"Via Quinto Sella, 118"},
...]

I really need to minimize the usage of bandwidth that a JSON response consumes. I can't seem to find a way to transform the view into a simple array. Suggestions?

Upvotes: 2

Views: 130

Answers (1)

Marcin Skórzewski
Marcin Skórzewski

Reputation: 2854

The response you are getting conforms to the Couch's REST based protocol. To reformat it two methods are provided: show functions and list functions. Basic idea is the same, but the first is suitable for retrieval documents and the list function is for you!

The list function runs the query inside the server and send the output arbitrary transformed with your JS code. API you will need is simple:

  • Fetch each record from the view with the getRow() function.
  • Export to the string (containing JSON) your JS object obj with toJSON(obj).
  • Send the output to the client with send(json).

If the map/reduce view URL with data is /mydb/_design/myapp/_view/mydocs-by-user and the list function name is mylist get the reformatted result to the client with the URL /mydb/_design/myapp/_list/mylist/mydocs-by-user.

Please refer to the list function documentation cited above and the chapter in the Guide for the longed tutorial.

Upvotes: 3

Related Questions