We talked a lot about schemas, structures, relations.
Now let's talk about schema validation
and with that, I'll come back to the data type thing
and also to our schema structure in general. You learned that mongodb is very flexible,
you can have totally different schemas or documents in one and the same collection
and that flexibility is a huge plus
but sometimes you want to lock down your flexibility here, you want to get rid of it. Sometimes you need a strict
schema because you know your application is going to fetch posts and it is going to access the title
on each post and it does expect that each title is a string
and for cases like this, schema validation can help you. Now what is schema validation?
Let's say we have an insert operation going on on our collection, on our posts collection maybe and
the same would be true for update or insertMany operations by the way,
so we're trying to add or edit some data in a collection.
If we add a validation schema and I will show you how you add one in the next lecture, if we added one,
then the schema will validate or the mongodb will validate the incoming data based on the schema we
defined and either it accepts it and then allows the write to the database or it rejects the incoming data,
hence your database is not touched and is not changed and the user gets an error.
To be precise, you can define schema validation in the way I'll show it in the next lecture and you can also define
which kinds of operations you want to validate and what you want to do if validation fails
with two settings you can add.
You can define which document should get validated
and what happens if it fails,
you can either set the validation level to strict which means all inserts and updates are checked or
to moderate
which means all inserts are checked but updates are only checked for documents which were valid before.
So if you had some invalid data in there because it existed before you set up a schema, then you could still
change these documents even if they don't fit your schema. For validation action,
you can decide whether you want to throw an error and not go on with the insert or update, so it will
not change your database data or if you only want to log a warning and proceed,
so then you would still write the data, you would still change the data but log a warning that it did not
fulfill your criteria.
And what you want to choose here really depends on your application,
if you're ok with incorrect data ending up in your database, you just want to be aware of it or if you
totally need to block it. Let's have a look at that in code next.