couchdbcouchdb-2.0fauxton

Creating a validation with CouchDB (Fauxton)


I store products in the following way in a CouchDB database:

{
  "_id": "1ce330a867a803fd10082c4513000fe5",
  "_rev": "4-a5eae6f790ea8b9cedea53db50a13fef",
  "type": "Product",
  "name": "Apple",
  "price": 1
}

I'd like to create a validation to make sure that every new document with the type Product has the field name. The only documentation I found was http://guide.couchdb.org/draft/validation.html After reading it I wrote/copied this validation:

function(newDoc, oldDoc, userCtx) {
  function require(field, message) {
    message = message || "Document must have a " + field;
    if (!newDoc[field]) throw({forbidden : message});
  }

  if (newDoc.type == "Product") {
    require("name");
  }
}

Than I use Fauxton to create it:

Screencast

But it doesn't work. I can create such a document without a name field. What do I do wrong?


Solution

  • You have to create a new design document. You need to specify the language field which will be JavaScript in your case.

    Then, you have to add the validate_doc_update field and fill it with your function.

    As a reference, you can look into the _replicator database for the _design/_replicator.

    Alternative

    On the command line it can be done with (beware of escaping the "):

    curl -X PUT http://127.0.0.1:5984/shop/_design/product_validation -d '{"validate_doc_update": "function(newDoc, oldDoc, userCtx) { if (newDoc.type == \"product\") { if (!newDoc[\"name\"]) { throw({forbidden: \"missing name\"}) } } }"}'