Update functions called from MyCouch Extension

179 Views Asked by At

I'm trying to call update functions from MyCouch. The documentation of Mycouch reports only an outdated example with Post method on _design documents. But how to consume an Update function

{
  "_id": "_design/artists",
  "language": "javascript",
  "views": {
    "albums": {
        "map": "function(doc) {  if(doc.$doctype !== 'artist') return;  emit(doc.name, doc.albums);}" 
    }
  }
};

client.Documents.Post(designDocumentAsJson);

How to execute the update function on _design couchDB pushing a new document ?

The couchDB documentation tells about this call

PUT /{db}/_design/{ddoc}/_update/{func}/{docid}
1

There are 1 best solutions below

0
On BEST ANSWER

PUT /{db}/_design/{ddoc}/_update/{func}/{docid}

Executes update function on server side for the specified document.
Parameters: 

    db – Database name
    ddoc – Design document name
    func – Update function name
    docid – Document ID

You can insert Design document like below to db: https://docs.couchdb.org/en/stable/api/ddoc/render.html#db-design-design-doc-update-update-name

{
  "_id": "_design/albums",
  "language": "javascript",
  "updates": {
    "addAlbum": "function(doc, req) {\n    if (!doc){\n      return [null, {'code': 400,\n                     'json': {'error': 'missed',\n                              'reason': 'no document to update'}}]\n    } else {\n        var body = JSON.parse(req.body);\n        doc.albums.push(body.album);\n        return [doc, {'json': {'status': 'ok'}}];\n    }\n}\n"
  }
}

function (Without stringifying):

function(doc, req) {
    if (!doc){
      return [null, {'code': 400,
                     'json': {'error': 'missed',
                              'reason': 'no document to update'}}]
    } else {
        var body = JSON.parse(req.body);
        doc.albums.push(body.album);
        return [doc, {'json': {'status': 'ok'}}];
    }
}

Example doc:

{
  "_id": "albumsId1",
  "albums": [
    1
  ]
}

After Api

Request:

POST http://localhost:5984/test/_design/albums/_update/addAlbum/albumsId1
Content-Type:application/json
Accept:application/json

{"album":2}

Response:

{
    "status": "ok"
}

doc after updating

{
  "_id": "albumsId1",
  "_rev": "19-7edb16db3bae388685f554138d562bd0",
  "albums": [
    1,
    2
  ]
}