MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

Good Practice - Setting the required property of a field that "does not exist"

I have 30 years experience with RDBMS, so MongoDB design principles are new to me. I’m also designing my app using TDD principles, which is also new to me. I’m writing an API to do all the database operations.

I was writing a test to check that an error is raised if an attempt is made to set the required property of a field that does not exist (in RDBMS terms) or does not have a document using that field (in MongoDB terms).

If I were using an RDBMS, then I would expect the RDBMS to raise an error and I wouldn’t even have to think about it. In MongoDB, if I add a required validator to a field which is not used (or doesn’t exist), then the validator is created without an error and any previously created documents fail validation. This behaviour by MongoDB is deliberate because it fits in with the principles of the flexibility of MongoDB.

My inclination is to only allow the required validator to be created on a non-existent if there are no documents in the collection. So, any new documents created will need to have a value in this field.

If the validator is created on a collection has documents, then they will fail validation and will need to be sorted out. In this scenario, the programmer should amend the documents first and add the validator once this has been done. The likelihood is that the creation of the validator is a programming error (perhaps the name of a field was spelled incorrectly), so an error should be raised.

What do you think?

Hi @Julie_Stenning,

You can use the $jsonSchema query operator to check existing documents for compliance with new or proposed schema validation. You can use this to assert that there are no invalid documents found before applying a new validator.

For example usage, see my DBA Stack Exchange answer on How to find all invalid document based on jsonSchema validator?.

Regards,
Stennie

Thanks Stennie. That helps me when I want to check whether or not the documents are valid. What is your view about whether or not I should add a required validator to a field that doesn’t exist?