Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using only JsonSchema with Mongoose possible?

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?

like image 738
Proximo Avatar asked Jan 21 '17 17:01

Proximo


People also ask

Which schema types are not supported by Mongoose?

Mongoose does not natively support long and double datatypes for example, although MongoDB does.

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

Can I use MongoDB and Mongoose together?

Connecting to MongoDBMongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose. connect() as shown below (for the tutorial we'll instead connect to an internet-hosted database). You can get the default Connection object with mongoose.


1 Answers

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

like image 143
mrtaz Avatar answered Oct 16 '22 04:10

mrtaz