8

I have an api using express, mongodb and I use AJV validation to validate the incoming requests.

//JSONSchema
var recordJsonSchema = {
     type: "object",
     properties: {
         name: { type: "string" },
         idNumber: { type: "number" },
         content: { type: "string" }
     },
     required: ['name','idNumber']
}

And I'd use this JSON schema to validate incoming requests like so.

app.post('/record', (req,res) => {
   let errors = ajv.inspect(req.body, recordJsonSchema)
   return errors ? res.send(errors) : res.send(this.handler(req));
})

This works fine and is very fast. I also like JsonSchema since it follows OpenAPI standards.

Unfortunately, in order to read/write to mongo via mongoose I also need to create a MongoSchema for Record. They are very similar but a bit different in how they handle required fields etc.

var recordSchema = new Schema({
   name: { type: "string", required: true },
   idNumber: { type: "number", required: true },
   content: { type: "string" }
})

So for my model of Record I have two schemas now. One for JSONschema and one for handling Mongo read/writes.

I'm looking for a way to cut MongoSchema, any suggestions?

Proximo
  • 6,235
  • 11
  • 49
  • 67
  • 1
    What was your solution? This is the exact issue I'm having. I don't want to use both if Mongoose already has it built in. – Gary Oct 30 '21 at 19:30
  • Did you managed to solve this at the end? I am facing the same issue. Thank you in advance and regards – Javier Guzmán Jun 01 '22 at 11:16
  • I ended up creating a function that converted JSON schema to a Mongo schema object. – Proximo Jun 01 '22 at 14:55

2 Answers2

2

Maybe this, seems like it imports your ajv schema from the entry and place it in the mongoose schema. https://www.npmjs.com/package/mongoose-ajv-plugin

mrtaz
  • 446
  • 1
  • 6
  • 16
0

I have faced with same problem. I think in new mongo 4.4 we can load ajv schema directly to mongodb https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/