veich
veich

Reputation: 539

How to convert JSON schema to mongoose schema

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)

Upvotes: 9

Views: 11400

Answers (1)

JohnSz
JohnSz

Reputation: 2049

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.

Upvotes: 2

Related Questions