How do I determine why a MongoDB document is failing validation?

As at MongoDB 3.2, there is no feedback on the reason document validation failed: the overall validation expression currently evaluates as either True ("OK") or False ("Document failed validation"). Validation behaviour can be adjusted with validationAction (error/warn) and validationLevel (strict/moderate/off) configuration options, but this does not provide any further context for validation failures.

If you want to have more detailed feedback, the recommended approach would be to add validation logic into your application rather than relying solely on server-side checks. Even with server-side validation, many checks are best done in application business logic to minimize round trips to the database server and provide more responsive feedback to the end user.

For example, user input for a web app (required fields, field formats, ...) should be validated in the browser before being submitted to your application or attempting to insert/update in the database.

However, it does make sense to validate at multiple levels to ensure data quality and some context to diagnose validation failures would be very useful. There is a relevant open feature request you can watch/up-vote in the MongoDB issue tracker: SERVER-20547: Expose the reason an operation fails document validation.

For more information you may also be interested in Document Validation - Part 1: Adding Just the Right Amount of Control Over Your Documents. This highlights some of the general pros & cons of document validation as at MongoDB 3.2, and includes a reference table for the outcome based on validationAction and validationLevel configuration options.


Of course the original answer is right, handling validation prior to arriving at the db is absolutely best practice, but as a practical matter if you need to chase it down like right now, you can temporarily remove validation from the Schema and then seeing what shows up in the Collection.

If a field was required but it shows up missing, empty, or misshapen at least it narrows your search. If the data looks right, have a look at the validations specified in the Schema.