Repository navigation
Validators
A collection definition can declare a
$jsonSchema validator, as a JSON string or a
BsonDocument (the schema itself, without the $jsonSchema wrapper).
[ManagedCollection("customers")]
public sealed class Customers : ICollectionDefinition<BsonDocument>
{
public void Define(CollectionBuilder<BsonDocument> collection) =>
collection.Validator.JsonSchema("""
{
"bsonType": "object",
"required": ["email", "tier"],
"properties": {
"email": { "bsonType": "string" },
"tier": { "enum": ["Standard", "Gold", "Platinum"] }
}
}
""")
.Level(ValidationLevel.Moderate)
.Action(ValidationAction.Warn);
}ValidationLevel |
Checks |
|---|---|
Strict (MongoDB's default) |
Every insert and update. |
Moderate |
Inserts, and updates to documents that are already valid. |
Constraint (9.0+) |
Every insert and update, and guarantees every document is valid. |
Off |
Nothing. |
ValidationAction |
On a failing write |
|---|---|
Error (MongoDB's default) |
Rejects it. |
Warn |
Allows it and logs the failure to the mongod log. |
ErrorAndLog (8.1+) |
Rejects it and logs it. |
Not declaring Level or Action leaves the server's setting alone.
The schema is created with the collection and changed in place with collMod.
- Field names are written as stored, not rendered through class maps.
- MongoDB's
$jsonSchemais draft 4 plusbsonType, without$ref,$schema,default,definitions,format,idortype: integer.
MongoDB doesn't check existing documents when a validator changes, only later writes. So before adding or changing one,
plan and up count the documents it would reject and show a few _ids.
validators.onInvalidDocuments |
|
|---|---|
warn (default) |
It's applied anyway, with a warning. |
fail |
The run stops with exit code 4. --allow-invalid-documents customers approves one collection. |
validators.countInvalidDocuments: false skips the count on very large collections.
- Deploy it with
ValidationAction.Warn. - Fix the data in a migration.
- Switch to
ValidationAction.Error.
A validator on the server that the definition doesn't declare is left alone and reported, unless
validators.prune: remove, which removes it and records it first.
Kevsoft.MigrateMongo ·
NuGet ·
Releases ·
Issues ·
Found a mistake? These pages live in
wiki/ on main; pull requests welcome.
Get started
Migrations
- Writing Migrations
- Transactions
- Recording Results
- Dependency Injection
- Custom Templates
- Adopting an Existing Database
Collections
- Managing Collections
- Indexes
- Search Indexes
- Collection Options
- Validators
- Views
- Undeclared Collections
Deploying
Connecting
Reference
Concepts