Anna Anna - 2 months ago 8
JSON Question

How can you require a field in an array in CouchDB?

Here is the little JSON file I have. I want the validate_doc_update function to require the address field in the destination array.

{
"Name": "Someone",
"secondary_id": "1111",
"destination": [
{
"address": "something"
}]
}

I have tried this (of course it is not working):

function(newDoc, oldDoc, userCtx){
if(!newDoc.destination.address){
throw({forbidden:'doc.address is required'});
}
}


Is there even a way to require a field in an array? or does couchDB not allow it?

Kul Kul
Answer

Assuming that any object in the destination array can contain address for validation to succeed, you can use the following validation function:

function(newDoc, oldDoc, userCtx) {
  if(newDoc.destination && newDoc.destination.length > 0){
    for(var i = 0; i < newDoc.destination.length; i++){
      if(newDoc.destination[i].address) return;
    }
  }
  throw({forbidden:'doc.address is required'});    
}

If you require all objects in the destination array to contain address, use the following validation function:

function(newDoc, oldDoc, userCtx) {
  if(newDoc.destination && newDoc.destination.length > 0){
    for(var i = 0; i < newDoc.destination.length; i++){
      if(!newDoc.destination[i].address) throw({forbidden:'doc.address is required'});
    }
    return;
  }
  throw({forbidden:'doc.address is required'});
}