Iam having a cosmos db collection with documents, now what I want is when I create a new document in that collection (iam using .net document DB API), can I validate some values. E.g
My document has a field Name
and I want that only Peter
or John
should be inserted. Does there exist a mechanism in cosmosdb so that I can do such validations or can I do them only from the application code?

- 942
- 7
- 23
3 Answers
As Gaurav Mantri commented that you could leverage Database triggers to validate the properties in your document as follows:
Note: The triggers are not automatically invoked, you need to explicitly specify the trigger(s) when you call the related operation. Here is the code sample for creating the new document, you could refer to it:
var result = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(
DatabaseId,
DocumentCollectionId),
doc,
new RequestOptions() {
PreTriggerInclude=new List<string>() { "validateDocContent" }
});
If the validation failed, you would get the exception as follows:
Moreover, here is a similar issue, you could follow here.

- 18,207
- 2
- 21
- 35
Does there exist a mechanism in cosmosdb so that I can do such validations or can I do them only from the application code?
As such no validations like these exist at the service level because these are specific to your application. You would need to handle them in your application code only.

- 128,066
- 12
- 206
- 241
-
Asked this question because in sql work there is a constraint like "Check" which does this : https://stackoverflow.com/questions/2441427/restrict-varchar-column-to-specific-values – Kayani Nov 28 '17 at 17:12
-
1I have not tried it but you can create a trigger (Before + Create) and put the check in there. That way you don't have to worry about putting this in application code. – Gaurav Mantri Nov 29 '17 at 02:44
MongoDb use JSON Schema to validate document on insert and update.
CosmosDb doesn't provide anything similar but,
CosmosDb provides Triggers cosmos-db/stored-procedures-triggers-udfs, azure-cosmosdb-js-server/samples/triggers/
One can use javascript-validator inside the trigger to validate the schema/document before inserting in the container.
I don't have a working example, but I am working on it.

- 114
- 17