Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate document before inserting in MongoDB using .NET driver

I am new to .NET development and an trying to develop a basic console app to insert data into MongoDB. I am successfully able to connect, create collections, insert, and query data using the .NET driver for MongoDB. My next step is to validate the data before I do an insert. I have found documentation and tried out validation in the shell and the pymongo driver, but am unable to find the .NET equivalent. Can someone point me towards some documentation or a tutorial? (I found a course on Mongo University, but it doesn't start for a couple months.)

Thanks in advance.

like image 894
Kat Avatar asked Nov 15 '25 22:11

Kat


2 Answers

Document Validation

I believe you are looking for document validation in MongoDB. It has been supported since version 3.2. You can see in the documentation, that there is

  • validationLevel to set which documents the validation rules apply to
  • validationAction to set whether a validation failure creates an error and the document is rejected, or a warning and the document is inserted.

This pushes the validation responsibility to the database instead of in your code. That can be nice if there are multiple clients accessing the database.

C# Driver

The mainline C# driver as well as the legacy C# driver support document validation. As you see in the documentation, you set a validator when you create a collection (or by using collMod to add a validator to an existing collection, but I won't discuss this further). The driver includes properties inside the CreateCollectionOptions class for the Validator document, the ValidationAction, and ValidationLevel. CreateCollectionOptions is the second argument you pass to the CreateCollection function. Here is the source code and a test that creates a collection with a simple validator and another.

like image 151
logan rakai Avatar answered Nov 17 '25 16:11

logan rakai


The documentation that you have found is for validating documents that have already been inserted into collection.

If you want to validate the document that you are about to insert, then I would suggest the following:

BSON supports a limited number of data types. All of them have their appropriate representations in .NET.

Use them to create a class that corresponds to your document structure. For example:

class dbEntry
{
    public BsonObjectId _id { get; set; }
    public string name { get; set; }
    public string ID { get; set; }
    public DateTime CreationDate { get; set; }
    public bool deleted { get; set; }
}

When you create an object of that class, values will need to conform to the data types you have defined. This is a pretty solid validation in .NET if you ask me.

like image 24
tonysepia Avatar answered Nov 17 '25 18:11

tonysepia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!