2

Is it possible to write a validation function to ensure a field of a new document is unique?

Imagine I'm trying to write a validation function that does not allow for two users to have the same email. Every time I create a new user, the validation function will be called and will probably look something like this:

function (newDoc, oldDoc) {
    //How do I get this array to contain the emails of all the users?
    var allEmail;

    if (allEmail.indexOf(newDoc.email) !== -1) {
        throw "This email adress is already taken";
    }
};

How can I fill the array allEmail to contain all emails of the users?

Is it possible to call views in the validation function?

arnoutaertgeerts
  • 2,232
  • 5
  • 29
  • 44
  • Possible duplicate of [Unique constraints in couchdb](http://stackoverflow.com/questions/1541239/unique-constraints-in-couchdb) – TimoSolo Feb 28 '17 at 11:47

2 Answers2

2

Not possible. Validation function only operates with updated doc and his previous revision and it cannot access to other documents. The only field that guaranteed to be unique is document _id. If it's possible and doesn't produce security/privacy issues, use email as doc _id to be ensure that it's unique.

Otherwise you have to create a view with target field as a key and check for it existence first before create a new doc on the client side. However, this logic easily becomes ruined when you'll replicate docs from other instance.

Kxepal
  • 4,659
  • 1
  • 19
  • 16
0

If the application is in offline, the above suggested solution how will react. Local pouch view can check and return the pouch results alone. There may be a high chance of same value entered from some other end and updated to couch db.

Do you have workaround for this case ?