How to create a "validate document update" on CouchDB 2?

1.9k Views Asked by At

I've read about validations (validate_doc_update) we can create on CouchDB, however I didn't figure out how I can create them. Can I do it through Fauxton?

Databases -> "mydb" -> Design Documents -> New Doc

Is this the way? Must I declare the function as string? I need an example please (there is any step-by-step in the docs).

Thanks.

2

There are 2 best solutions below

0
On

Manually writing design documents is an option, you simply need to write it out as a string, since JSON doesn't support writing functions as values. (as you've discovered)

However, I would strongly recommend using other tools to manage your design documents. In particular, the CLI tool couchapp, and related clones (eg: erica) allow you to use a filesystem to represent your design document. (including view functions, validation functions, etc)

Instead of using the fauxton/futon editor (which get clumsy very quickly, especially for non-trivial functions), you can write a plain .js file with your validation function, and it can be formatted and uploaded to CouchDB automatically. (the same applies to views, shows/lists, etc)

Using this approach is much easier and safer to maintain, and something I highly recommend whenever working with CouchDB.

0
On

I figured this out. Here is the step-by-step:

Through Fauxton

Navigate to: Databases -> [select your database name here] -> All Documents -> New Doc, then fill up the text area with your desired validation using the JSON boilerplate below and click Save:

{
  "_id": "_design/my_validation_name",
  "validate_doc_update": "function(newDoc, oldDoc, userCtx) {throw({forbidden : 'not able now!'});}"
}

Through curl

curl -X PUT http://127.0.0.1:5984/my_database/_design/my_validation_name -d '{"validate_doc_update": "function(newDoc, oldDoc, userCtx) { throw({forbidden: \"not able now!\" });}"}'

Important: The DocID must be prefixed by "_design/" and the key of the function must be "validate_doc_update". Note the function as string.

After the validation set, if we try to create a document you must see the error "not able now!"..

curl -X PUT http://127.0.0.1:5984/my_database/foo -d '{"foo" : "bar"}'
# {"error":"forbidden","reason":"not able now!"}