javascriptcouchdbdesign-documents

How to ensure certain fields are included in a CouchDB database?


I am trying to find a way of ensuring that certain content is present in the documents of a CouchDB database. I thought the best way of doing this would be with a "validate_doc_update" design document. I had created one in the past that checked whether a user was authorized to make changes to the database so I tried to include this additional code there. However it is not recognized as compileable code in CouchDB and I am unsure why (see code below). Does anyone know where I have messed up with this code to make it not compile or if there is a better way to go about ensuring certain Fields are included in an updated document?

This is included in a design document within the same database called "_design/BGdesign":

function(newDoc, oldDoc, userCtx, secObj){
if ('_admin' in userCtx.roles) return; // skip anonymous in Admin Party case
if (userCtx.roles.indexOf('testAdmin') == -1) {
    throw({forbidden: "Not Authorized"});
    }
}
if (newDoc.artistName === undefined) {
    throw({forbidden: 'Document must have a artistName'});
}
if (newDoc.currentLocation === undefined) {
    throw({forbidden: 'Document must have a currentLocation'});
}
if (newDoc.dateMade === undefined) {
    throw({forbidden: 'Document must have a dateMade.'});
}
if (newDoc.description === undefined) {
    throw({forbidden: 'Document must have a description.'});
}
if (newDoc.name === undefined) {
    throw({forbidden: 'Document must have a name.'});
}
if (newDoc.owner === undefined) {
    throw({forbidden: 'Document must have an owner.'});
}
if (newDoc.tags === undefined) {
    throw({forbidden: 'Document must have tags.'});
}
if (newDoc.uploaded === undefined) {
    throw({forbidden: 'Document must have an uploaded date.'});
}

}


Solution

  • Mismatched curly brackets were the cause of the problem. If there is any more efficient/'proper' ways to do what I'm trying to do (short of compressing the if statements into a single IF statement as I am about to do) I would greatly appreciate the information.