User defined Schemas for Validation


Potentially super noob question, but could not find anything here or at stackoverflow.

In my application (currently working on the backend with express), I want users to store data based on their own JSON schema definitions. So they should be able to store a JSON schema and then later on upload data that should be validated using this schema. The data is similar (in a way that I want to put it in the same collection), but still different (in the way that it needs their own validation).

What is the best way to do this?
I was planning on having just one collection, make users submit the schemaID they want to use to validate their data, get this schema from the database and use it for validation. For this, my question would be how to properly create a collection of JSON schemas.

However, MongoDB uses these schemas for collections, anyway, so should I rather create individual (user defined) collections for each submitted schema so I can take advantage of the built-in validation? If yes, I then have to ask somewhere else how to dynamically create the respective routes in my applicationn:)

Thanks in advance.

Hi Nicholas, welcome to the community!

If you want to use a single collection then you could use a 3rd party schema validation library. e.g., if you’re using Node then there’s AJV which uses JSON Schema. Your document could then looks something like this:

    user: "Nicholas",
    schema: { ... }, 
    payload: { ... }

Then when your app has data to store, it can fetch the document from MongoDB, validate the data against the schema, and if it passes store it in the payload attribute.

1 Like

Thanks, I have done it almost exactly like this now.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.