CouchDB, Validation functions
18 Nov
The last CouchDB post was about Design Documents, and we described how it’s possible to create views directly on it. Now this post is about another part of Design Documents and it’s fundamental on a CouchDB project context.
We already know that CouchDB is a schema free document oriented database, this means that there are no constraints when we create / update documents ! now let’s imagine that every user of the CouchDB application can create any kind of document with what he wants .. we need to deal with data consistency and for that we’ll need Validation Functions !
The Validation Function definition :
It’s important to know that Validation functions are optional, if you don’t define them there will be no check. Also validation functions are stored on the Design Document under the “validate_doc_update” field.
function(newDoc, oldDoc, userCtx) {}
- newDoc is for the incoming document.
- oldDoc is the current saved document.
- userCtx the user object doing the request.
Now let’s try to add a validation function to a design document, what you need is to open Futon then :
choose a database > view “Design documents” > Choose a design
Now edit the document and add this at the end of document defintion :
"validate_doc_update": "function(newDoc, oldDoc, userCtx) {
throw({forbidden : 'you are not allowed !'
});}"
You will get something like this (you’ll need to save the document) :
Okey now let’s try to create an new document using Curl :
curl -X PUT http://127.0.0.1:5984/contacts/contactValidation -d '{"name" : "contact validation"}'
//return
{"error":"forbidden","reason":"you are not allowed !"}
Et voilà ! the validation function has thrown an exception and no more document creation / update is possible ! now lets tune it a little bit. We are using a contact database so we’ll not permit creation of document without name, and phone fields :
function(newDoc, oldDoc, userCtx) {
function require(field){
var message = field + ' is required';
if(!newDoc[field]){
throw({'forbidden':message})
}
}
require('name');
require('phone')}
Okey let’s try again with curl :
curl -X PUT http://127.0.0.1:5984/contacts/contactValidation -d '{"name" : "contact validation"}'
{"error":"forbidden","reason":"phone is required"}
And now we add required fields :
curl -X PUT http://127.0.0.1:5984/contacts/contactValidation -d '{"name" : "contact validation", "phone":"123-1111"}'
{"ok":true,"id":"contactValidation","rev":"1-8330cb19d688702b4c24e3ae468f31f2"}
And it’s working ! as you can see it’s simple to check document consistency with simple javascript tests ! Hope you like this post.
Comments
Powered by Facebook Comments

















Application Developer and Technical Project Manager in a wide variety of business applications. Particularly interested in client/server and relational database design using MySQL. Always interested in migration projects, as well as close interaction with the DB manufacturers.
No comments yet