Does CouchDB supports referential integrity?

前端 未结 3 2099
一个人的身影
一个人的身影 2021-02-07 17:56

I am new to CouchDB and learning about it. I did not come across CouchDB support for referential integrity. Can we create a foreign key for a field in the CouchDB document?

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 18:20

    While not possible to create an FK constraint, it is possible using Couch's Validate function

    function(newDoc, oldDoc, userCtx, secObj) {
        if(newDoc && newDoc.type) switch(newDoc.type){
            case 'fish':
                var allSpecies = ['trout','goldfish'];
                if(!allSpecies.contains(newDoc.species)){
                    throw({forbidden : 'fish must be of a know species'});
                }
                break;
            case 'mammals':
                if(!['M','F'].contains(newDoc.sex)){
                    throw({forbidden : 'mammals must have their sex listed'});
                }
                break;
        }
    }
    

    Now, if a person were really clever (I'm not), they might do a call out to the DB itself for the list of Species... that would be a foreign key.

    You may also want to read up on: How do I DRY up my CouchDB views?

提交回复
热议问题