Skip to content

(DOCS-14761): Validation failures include description #5864

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 120 additions & 51 deletions source/core/schema-validation.txt
Original file line number Diff line number Diff line change
Expand Up @@ -144,21 +144,20 @@ query expression:

:ref:`query operators <query-selectors>`

Behavior
--------
Behavior and Examples
---------------------

Validation occurs during updates and inserts. When you add validation to
a collection, existing documents do not undergo validation checks until
modification.

Validation on Existing Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To perform validation checks on existing documents, use the
:dbcommand:`validate` command or the :method:`db.collection.validate()`
shell helper.


Existing Documents
~~~~~~~~~~~~~~~~~~

The ``validationLevel`` option determines which operations MongoDB
applies the validation rules:

Expand All @@ -176,7 +175,7 @@ documents:

.. code-block:: json

db.contacts.insert([
db.contacts.insertMany([
{ "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London", "status": "Complete" },
{ "_id": 2, "name": "Ivan", "city": "Vancouver" }
])
Expand All @@ -194,11 +193,11 @@ collection:
properties: {
phone: {
bsonType: "string",
description: "must be a string and is required"
description: "phone must be a string and is required"
},
name: {
bsonType: "string",
description: "must be a string and is required"
description: "name must be a string and is required"
}
}
} },
Expand Down Expand Up @@ -230,12 +229,12 @@ validation rule we created above that requires ``name`` to be a string.

.. code-block:: javascript

db.contacts.update(
db.contacts.updateOne(
{ _id: 1 },
{ $set: { name: 10 } }
)

db.contacts.update(
db.contacts.updateOne(
{ _id: 2 },
{ $set: { name: 20 } }
)
Expand All @@ -247,48 +246,44 @@ document did not meet the initial criteria when validation was added.

.. code-block:: javascript
:copyable: false
:emphasize-lines: 9-27

// _id: 1
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation",
"errInfo" : {
"failingDocumentId" : 1,
"details" : {
"operatorName" : "$jsonSchema",
"schemaRulesNotSatisfied" : [
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: 1,
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
"operatorName" : "properties",
"propertiesNotSatisfied" : [
{
"propertyName" : "name",
"details" : [
{
"operatorName" : "bsonType",
"specifiedAs" : {
"bsonType" : "string"
},
"reason" : "type did not match",
"consideredValue" : 10,
"consideredType" : "double"
}
]
}
]
}
]
propertyName: 'name',
description: 'name must be a string and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'string' },
reason: 'type did not match',
consideredValue: 10,
consideredType: 'int'
}
]
}
]
}
}
}
})
]
}
}

// _id: 2
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 0,
upsertedCount: 0
}

To disable validation entirely, you can set ``validationLevel`` to
``off``.
Expand Down Expand Up @@ -333,16 +328,13 @@ Schema validator:
validationAction: "warn"
} )

With the ``warn`` :collflag:`validationAction`, MongoDB logs any
violations but allows the insertion or update to proceed.

For example, the following insert operation violates the validation rule:

.. code-block:: javascript

db.contacts2.insert( { name: "Amanda", status: "Updated" } )

However, since the ``validationAction`` is ``warn`` only, MongoDB only
However, since the ``validationAction`` is ``warn``, MongoDB only
logs the validation violation message and allows the operation to
proceed. Run the following command to view the MongoDB logs:

Expand Down Expand Up @@ -384,6 +376,83 @@ readability) contains information like this:
\"specifiedAs\":{\"required\":[\"phone\"]},
\"missingProperties\":[\"phone\"]}]}}}}"

.. _validation-description-example:

Use Title and Description Fields to Clarify Validation Rules
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/fact-5.1-schema-validation-description-overview.rst

Consider a ``users`` collection with the following schema validation:

.. code-block:: javascript

db.runCommand( {
collMod: "users",
validator: { $jsonSchema: {
bsonType: "object",
title: "Email validation",
properties: {
email: {
"bsonType": "string",
"pattern": "^@mongodb\.com$",
"description": "Email address must end with '@mongodb.com'"
},
}
} },
validationLevel: "moderate"
} )

The ``pattern`` field indicates that all ``email`` fields must
end with ``@mongodb.com``. If you try to insert a document that
does not match the pattern, MongoDB includes the validation
``title`` and ``description`` in the error output:

Input:

.. code-block:: javascript

db.users.insertOne( { "name": "Amelia Morrison", "email": "a.morrison@nwsueicn.com" } )

Output:

.. code-block:: javascript
:copyable: false
:emphasize-lines: 6,13

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("614a10bab93bbd15dd2e2eb6"),
details: {
operatorName: '$jsonSchema',
title: 'Email validation',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'email',
description: "Email address must end with '@mongodb.com'",
details: [
{
operatorName: 'pattern',
specifiedAs: { pattern: '^@mongodb.com$' },
reason: 'regular expression did not match',
consideredValue: 'a.morrison@nwsueicn.com'
}
]
}
]
}
]
}
}

.. note::

The validation error output is formatted differently in the legacy
``mongo`` shell.

Restrictions
------------

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Starting in MongoDB 5.1, when a document fails :ref:`schema validation
<schema-validation-overview>`, MongoDB includes the validation ``title``
and ``description`` in the error response. You can use these fields to
provide a clearer explanation of the validation when the rules
are not immediately clear, such as when using regular expressions.
5 changes: 4 additions & 1 deletion source/reference/operator/query/jsonSchema.txt
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,10 @@ Available Keywords
* - description
- N/A
- string
- A string that describes the schema and has no effect.
- A string that describes the schema and has no effect on
validation. Starting in MongoDB 5.1, if the ``description`` field
is specified, MongoDB includes the ``description`` in the error
output when a document fails validation.

.. _jsonSchema-extension:

Expand Down
7 changes: 7 additions & 0 deletions source/release-notes/5.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ If the new parameter
the :ref:`query explain plan output
<explain-results-enhanced-execution>`.

Schema Validation Errors Contain Description Field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/fact-5.1-schema-validation-description-overview.rst

For an example, see :ref:`validation-description-example`.

.. _5.1-rel-notes-repl-sets:

Replica Sets
Expand Down