6
votes

Is there a way to take valid JSON schema like the one below and turn it into mongoose schema?

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "some desc",
  "title": "Product",
  "type": "object",
  "properties": {
    "endpoints": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "poi": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "location_name": {
            "type": "string"
          },
          "distance": {
            "type": "string"
          }
        }
      }
    }
  }
}

This seems so basic and simple to me but I haven't found anything on the net.
There are bunch of examples on how to get JSON schema and there are bunch of examples how to create mongoose schema from objects like this:
const newSchema = new mongoose.Schema({ name: String });

If I try to put JSON schema directly I get an error

node_modules/mongoose/lib/schema.js:674
    throw new TypeError('Undefined type `' + name + '` at `' + path +
    ^

TypeError: Undefined type `Http://json-schema.org/draft-04/schema#` at `$schema`
  Did you try nesting Schemas? You can only nest using refs or arrays.

But I could not find anywhere on the net transfer from one type to another.
Anyone had this issue before?

EDIT:

This question was conceptually incorrect.
Basically what you do is validate JSON schema against the data before saving it to DB. You do this using jsonschema from npm or some other.
So data validating step is not directly linked with saving to DB step.
I thought you can apply JSON schema to MongoDB schema but that was not true. (especially when you have deeply nested objects - then it's a mess)

2
What do you mean transfer from one type to another is nowhere to be seen?Edgar
I mean I could not find it on the internet by googling.veich
And what is wrong with const newSchema = new mongoose.Schema(YOUR_JSON_SCHEMA); in your situation?Edgar
I get an error: ``` .../node_modules/mongoose/lib/schema.js:674 throw new TypeError('Undefined type ' + name + ' at ' + path + ^ TypeError: Undefined type Http://json-schema.org/draft-04/schema#` at $schema Did you try nesting Schemas? You can only nest using refs or arrays. ```veich
I think you should convert all nested object to new Schema too.Edgar

2 Answers

2
votes

I have been looking into this. Since you placed a node tag on your question, I found these npm repos:

Both are working so far.

They are both a few years old. The former (TypeScript) has more recent commits. I may end up liking the latter more.