Hullo, I have a crux to bear with Mongoose. Is there a way of using JSON-Shema with Mongoose Schemas? Say I want to define my API data schema using a standard like JSON-Schema, because it's nice. It seems like I need to define it again when I want to use Mongoose / MongoDB! That's quite some ugly duplication I like to avoid. Ideally, changing the JSON-Schema definition would also change the MongoDB schema. A similar problem would appear if I would use JOI.JS validation library. Has anyone found a solution to that? Or is there an alternative approach?
thanks
To follow along with this tutorial, you'll need a MongoDB Atlas account and to download MongoDB Compass. JSON (JavaScript Object Notation) is a simple and lightweight text-based data format. JSON Schema is an IETF standard providing a format for what JSON data is required for a given application and how to interact with it.
JSON Schema is a specification for JSON based format for defining the structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema − Describes your existing data format. Clear, human- and machine-readable documentation. Complete structural validation, useful for automated testing.
To use Mongoose without defining a schema, we can define a field with the Mixed data type. to define the Any schema that has the any property set to the mixed type by setting the any property to {} or Schema.Types.Mixed. As a result, we can set any value as the value of any.
MongoDB also lets you enforce a schema to validate your data and maintain a data structure. We will use MongoDB Atlas and MongoDB Compass to demonstrate how.
Try this library: https://www.npmjs.com/package/json-schema-to-mongoose There are others out there too. I created json-schema-to-mongoose
since the other libraries didn't quite fit my needs.
Also, I like to generate the json-schema
from TypeScript
using Typson
. It makes it so the json-schema
is more statically typed.
Update
It appears the Typson
project is dead. Here's another (typescript-json-schema) project which does the same thing, although I've never used it.
Chiming in here since I've also run into this problem and found a solution that is alternative to the suggestions provided.
One can use https://github.com/nijikokun/generate-schema to take a plain JS object and convert it to both JSON Schema and a Mongoose Schema. I find this tool to be easier in the case of retrofitting existing code with validation and persistence since you will likely already have an example object to start with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With