sebbulon
sebbulon

Reputation: 623

define a schema with JSON-Schema and use Mongoose?

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

Upvotes: 7

Views: 4529

Answers (2)

Jon49
Jon49

Reputation: 4606

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.

Upvotes: 8

Nicholas J. Arnold
Nicholas J. Arnold

Reputation: 324

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.

Upvotes: 2

Related Questions