1

I would like to see if a document exists in the database that has the name field "name" set to "a name" before allowing a new document to be added to the database.

I this possible in CouchDB using update handlers (inside design documents)?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42

2 Answers2

0

Seems you are looking for a unique constraint in CouchDB. The only unique constraint supported by CouchDB is based on the document ID.

You should include your "name" attribute value into the document ID if you would like to have the document unicity based on it.

Validate document update functions defined in desing documents can only use the data of the document being created/updated/deleted, it can no use data from other documents in the database.

Yo can find a similar question here.

Juanjo Rodriguez
  • 2,103
  • 8
  • 19
0

This is not widely known, but _update endpoint allowed to return a doc with _id prop different from requested. It means, in your case, you need to have an unique document say _id:"doc-name", which will serve as a constraint.

Then you call smth like POST _design/whatever/_update/saveDependentDoc/doc-name, providing new doc with different _id as a request body.

Your _update function will effectively receive two docs as an input (or null and newDoc if constraint doc is missing). The function then decides what should it do: return received doc to persist it, or return nothing.

The solution isn’t a full answer to your question, however it might be helpful in some cases.

This trick only works for updating existing docs if you know revision, for sure.

ermouth
  • 835
  • 7
  • 12