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?