7

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

sebbulon
  • 613
  • 7
  • 21
  • 1
    I'm sure it's possible to take your json-schema and automatically convert it to a mongoose schema using javascript. at the end of the day, they're just objects once you parse it. – Kevin B Mar 24 '15 at 17:34
  • while that's fair enough, I was wondering if someone did something like that in the past and made that effort available to everyone, as it appears like a pretty obvious problem for me. I researched tools and couldn't find one so far. – sebbulon Mar 24 '15 at 17:38
  • 1
    https://www.npmjs.com/package/json-schema-converter – Kevin B Mar 24 '15 at 17:42
  • 2
    I updated json-schema-converter to https://www.npmjs.com/package/json-schema-to-mongoose since it didn't appear that json-schema-converter was being maintained anymore. – Jon49 Jun 05 '15 at 20:47

2 Answers2

8

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.

Jon49
  • 4,444
  • 4
  • 36
  • 73
2

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.

Nicholas J. Arnold
  • 324
  • 1
  • 2
  • 10