Kayani
Kayani

Reputation: 972

Validating strings in cosmosdb collection

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?

Upvotes: 2

Views: 1655

Answers (3)

Dipak Yadav
Dipak Yadav

Reputation: 114

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.

Upvotes: 0

Bruce Chen
Bruce Chen

Reputation: 18465

As Gaurav Mantri commented that you could leverage Database triggers to validate the properties in your document as follows:

enter image description here

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:

enter image description here

Moreover, here is a similar issue, you could follow here.

Upvotes: 2

Gaurav Mantri
Gaurav Mantri

Reputation: 136216

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.

Upvotes: 0

Related Questions