Define a schema using JSON-Schema and use Mongoose?

Hello, I have a serious problem with Mongoose. Is there a way to use JSON-Shema with Mongoose schemas? Let's say I want to define my API data schema using a standard such as JSON-Schema, because it is good. It seems I need to define it again when I want to use Mongoose / MongoDB! This is a pretty ugly duplication that I like to avoid. Ideally, changing the JSON-Schema definition would also change the MongoDB schema. A similar problem would occur if I used the JOI.JS validation library. Has anyone found a solution? Or is there an alternative approach?

thanks

+5
source share
2 answers

Try this library: https://www.npmjs.com/package/json-schema-to-mongoose There are others. I created json-schema-to-mongoose , as other libraries did not quite meet my needs.

Also, I like to generate json-schema from TypeScript using Typson . This makes it so that json-schema more statically typed.

+5
source

Let's move on here, as I also ran into this problem and found a solution alternative to the proposed proposals.

You can use https://github.com/nijikokun/generate-schema to accept a simple JS object and convert it to both a JSON schema and a Mongoose schema. I believe that this tool will be easier if you re-equip existing code with verification and preservation, since you most likely already have an example object to start with.

+2
source

Source: https://habr.com/ru/post/1216016/


All Articles