All Projects → DScheglov → mongoose-schema-jsonschema

DScheglov / mongoose-schema-jsonschema

Licence: MIT License
Mongoose extension that allows to build json schema for mongoose models, schemes and queries

Programming Languages

javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to mongoose-schema-jsonschema

mongoose-keywords
Mongoose plugin that generates a keywords path combining other paths values
Stars: ✭ 23 (-73.86%)
Mutual labels:  mongoose-schema, mongoose
json2object
Type safe Haxe/JSON (de)serializer
Stars: ✭ 54 (-38.64%)
Mutual labels:  json-schema
FlipED
A LMS built specifically for Thailand's Education 4.0 system.
Stars: ✭ 24 (-72.73%)
Mutual labels:  mongoose
fhir-fuel.github.io
Place to prepare proposal to FHIR about JSON, JSON-Schema, Swagger/OpenAPI, JSON native databases and other JSON-frendly formats (yaml, edn, avro, protobuf etc) and technologies
Stars: ✭ 20 (-77.27%)
Mutual labels:  json-schema
shopping-cart
A full-fledged package to build an e-commerce application for iOS and Android similar to Myntra/JackThreads. Available with beautiful design and necessary features along with screen for Dashboard and Mobile app. Build using React Native, Expo, React, GraphQL, Apollo Client, Node and MongoDB.
Stars: ✭ 64 (-27.27%)
Mutual labels:  mongoose
schemaorg-jsd
JSON Schema validation for JSON-LD files using Schema.org vocabulary.
Stars: ✭ 16 (-81.82%)
Mutual labels:  json-schema
mongoolia
Keep your mongoose schemas synced with Algolia
Stars: ✭ 58 (-34.09%)
Mutual labels:  mongoose
node-blog-app
🌐 A node+espress+mongoose+react+nextjs blog
Stars: ✭ 12 (-86.36%)
Mutual labels:  mongoose
cti-stix2-json-schemas
OASIS TC Open Repository: Non-normative schemas and examples for STIX 2
Stars: ✭ 75 (-14.77%)
Mutual labels:  json-schema
yajsv
Yet Another JSON Schema Validator [CLI]
Stars: ✭ 42 (-52.27%)
Mutual labels:  json-schema
express-mongoose-es8-rest-api
A Boilerplate for developing Rest api's in Node.js using express with support for ES6,ES7,ES8 ,Mongoose,JWT for authentication,Standardjs for linting
Stars: ✭ 20 (-77.27%)
Mutual labels:  mongoose
najs-eloquent
Use Mongoose in Typescript with elegant syntax. Inspired by Laravel Eloquent. Works with Node JS.
Stars: ✭ 26 (-70.45%)
Mutual labels:  mongoose
summary1
个人总结 持续更新 欢迎提出各种issues
Stars: ✭ 13 (-85.23%)
Mutual labels:  mongoose
timeoff-server
TimeOff is an application that allows companies' employees to set vacations before they begin taking their time off. Implemented in modern tech stack i.e. Node, Express, MongoDB.
Stars: ✭ 33 (-62.5%)
Mutual labels:  mongoose
ack-nestjs-mongoose
NestJs Boilerplate. Authentication (OAuth2), Mongoose, MongoDB , Configuration, Multi Languages (i18n), etc. Advance Example 🥶. NestJs v8 🥳🎉. Production Ready 🚀🔥
Stars: ✭ 81 (-7.95%)
Mutual labels:  mongoose
hiroki
create a REST api faster than ever
Stars: ✭ 13 (-85.23%)
Mutual labels:  mongoose
nodejs express template
🐼 source dummy Nodejs
Stars: ✭ 13 (-85.23%)
Mutual labels:  mongoose
fileupload-nodejs
MongoDB file upload using NodeJS and Mongo GridFS
Stars: ✭ 54 (-38.64%)
Mutual labels:  mongoose
value-app
Calculate the per-use value of purchases over time.
Stars: ✭ 14 (-84.09%)
Mutual labels:  mongoose
opis-error-presenter
JSON-schema error presenter for opis/json-schema library
Stars: ✭ 17 (-80.68%)
Mutual labels:  json-schema

Build status Coverage Status npm downloads David NPM

mongoose-schema-jsonschema

The module allows to create json schema from Mongoose schema by adding jsonSchema method to mongoose.Schema, mongoose.Model and mongoose.Query classes

Contents


Installation

npm install mongoose-schema-jsonschema

Schema Build Configuration

Since v1.4.0 it is able to configure how jsonSchema() works.

To do that package was extended with config function.

const config = require('mongoose-schema-jsonschema/config');

config({
  // ... options go here
});

Currently there are two options that affects build process:

  • forceRebuild: boolean -- mongoose-schema-jsonschema caches json schemas built for mongoose schemas. That means we cannot built updated jsonSchema after some updates were made in the mongoose schema that already has jsonSchema. To resolve this issue the forceRebuild was added (see sample bellow)

  • fieldOptionsMapping: { [key: string]: string } | Array<string|[string, string]> - allows to specify how to convert some custom options specified in the mongoose field definition.

const mongoose = require('mongoose-schema-jsonschema')();
const config = require('mongoose-schema-jsonschema/config');

const { Schema } = mongoose;

const BookSchema = new Schema({
  title: { type: String, required: true, notes: 'Book Title' },
  year: Number,
  author: { type: String, required: true },
});

const fieldOptionsMapping = {
  notes: 'x-notes',
};

config({ fieldOptionsMapping });
console.dir(BookSchema.jsonSchema(), { depth: null });

config({ fieldOptionsMapping: [], forceRebuild: true }); // reseting
console.dir(BookSchema.jsonSchema(), { depth: null });

Output:

{
  type: 'object',
  properties: {
    title: { type: 'string', 'x-notes': 'Book Title' },
    year: { type: 'number' },
    author: { type: 'string' },
    _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
  },
  required: [ 'title', 'author' ]
}
{
  type: 'object',
  properties: {
    title: { type: 'string' },
    year: { type: 'number' },
    author: { type: 'string' },
    _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
  },
  required: [ 'title', 'author' ]
}

Samples

Let's build json schema from simple mongoose schema

const mongoose = require('mongoose');
require('mongoose-schema-jsonschema')(mongoose);

const Schema = mongoose.Schema;

const BookSchema = new Schema({
  title: { type: String, required: true },
  year: Number,
  author: { type: String, required: true },
});

const jsonSchema = BookSchema.jsonSchema();

console.dir(jsonSchema, { depth: null });

Output:

{
  type: 'object',
  properties: {
    title: { type: 'string' },
    year: { type: 'number' },
    author: { type: 'string' },
    _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
   },
  required: [ 'title', 'author' ]
}

The mongoose.Model.jsonSchema method allows to build json schema considering the field selection and population

const mongoose = require('mongoose');
require('mongoose-schema-jsonschema')(mongoose);

const Schema = mongoose.Schema;

const BookSchema = new Schema({
  title: { type: String, required: true },
  year: Number,
  author: { type: Schema.Types.ObjectId, required: true, ref: 'Person' }
});

const PersonSchema = new Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  dateOfBirth: Date
});

const Book = mongoose.model('Book', BookSchema);
const Person = mongoose.model('Person', PersonSchema)

console.dir(Book.jsonSchema('title year'), { depth: null });
console.dir(Book.jsonSchema('', 'author'), { depth: null });

Output:

{
  title: 'Book',
  type: 'object',
  properties: {
    title: { type: 'string'  },
    year: { type: 'number'  },
    _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
  }
}
{
  title: 'Book',
  type: 'object',
  properties: {
    title: { type: 'string'  },
    year: { type: 'number'  },
    author: {
      title: 'Person',
      type: 'object',
      properties: {
        firstName: { type: 'string'  },
        lastName: { type: 'string'  },
        dateOfBirth: { type: 'string', format: 'date-time'  },
        _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$'  },
        __v: { type: 'number' }
       },
      required: [ 'firstName', 'lastName' ],
      'x-ref': 'Person',
      description: 'Refers to Person'
     },
    _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$'  },
    __v: { type: 'number' }
   },
  required: [ 'title', 'author' ]
}
const mongoose = require('mongoose');
const extendMongooose = require('mongoose-schema-jsonschema');

extendMongooose(mongoose);

const { Schema } = mongoose;

const BookSchema = new Schema({
  title: { type: String, required: true  },
  year: Number,
  author: { type: Schema.Types.ObjectId, required: true, ref: 'Person' }
});

const Book = mongoose.model('Book', BookSchema);
const Q = Book.find().select('title').limit(5);


console.dir(Q.jsonSchema(), { depth: null });

Output:

{
  title: 'List of books',
  type: 'array',
  items: {
    type: 'object',
    properties: {
      title: { type: 'string'  },
      _id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
    }
   },
  maxItems: 5
}

Validation tools

Created by mongoose-schema-jsonschema json-schema's could be used for document validation with:

Specifications

mongoose.Schema.prototype.jsonSchema

Builds the json schema based on the Mongooose schema. if schema has been already built the method returns new deep copy

Method considers the schema.options.toJSON.virtuals to included the virtual paths (without detailed description)

Declaration:

function schema_jsonSchema(name) { ... }

Parameters:

  • name: String - Name of the object
  • Returns Object - json schema

mongoose.Model.jsonSchema

Builds json schema for model considering the selection and population

if fields specified the method removes required constraints

Declaration:

function model_jsonSchema(fields, populate) { ... }

Parameters:

  • fields: String|Array|Object - mongoose selection object
  • populate: String|Object - mongoose population options
  • Returns Object - json schema

mongoose.Query.prototype.jsonSchema

Builds json schema considering the query type and query options. The method returns the schema for array if query type is find and the schema for single document if query type is findOne or findOneAnd*.

In case when the method returns schema for array the collection name is used to form title of the resulting schema. In findOne* case the title is the name of the appropriate model.

Declaration:

function query_jsonSchema() { ... }

Parameters:

  • Returns Object - json schema

Custom Schema Types Support

If you use custom Schema Types you should define the jsonSchema method for your type-class(es).

The base functionality is accessible from your code by calling base-class methods:

newSchemaType.prototype.jsonSchema = function() {
  // Simple types (strings, numbers, bools):
  const jsonSchema = mongoose.SchemaType.prototype.jsonSchema.call(this);

  // Date:
  const jsonSchema = Types.Date.prototype.jsonSchema.call(this);

  // ObjectId
  const jsonSchema = Types.ObjectId.prototype.jsonSchema.call(this);

  // for Array (or DocumentArray)
  const jsonSchema = Types.Array.prototype.jsonSchema.call(this);

  // for Embedded documents
  const jsonSchema = Types.Embedded.prototype.jsonSchema.call(this);

  // for Mixed documents:
  const jsonSchema = Types.Mixed.prototype.jsonSchema.call(this);

  /*
   *
   * Place your code instead of this comment
   *
   */

   return jsonSchema;
}

Releases

  • version 1.0 - Basic functionality
  • version 1.1 - Mongoose.Query support implemented
  • version 1.1.5 - uuid issue fixed, ajv compliance verified
  • version 1.1.8 - Schema.Types.Mixed issue fixed
  • version 1.1.9 - readonly settings support added
  • version 1.1.11 - required issue fixed issue#2
  • version 1.1.12 - mixed-type fields description and title support added (fix for issue: issue#3)
  • version 1.1.15 - support for [email protected] ensured issue#8
  • version 1.3.0
    • nullable types support (as union: [type, 'null'])
    • examples option support issue#14
    • support for fields dynamicly marked as required issue#16
    • Node support restricted to 8.x, 9.x, 10.x, 12.x
    • Monggose support restricted to 5.x
    • Development:
      • migrated from mocha + istanbul to jest
      • added eslint
  • version 1.3.1 - support minlenght and maxlength issue#21
  • version 1.4.0 - broken - schema build configurations (forceRebuild and fieldOptionsMapping)
  • version 1.4.2 - fix for broken version 1.4.0 issue#22
  • version 1.4.4 - fix for field constaints issue#25
  • version 2.0.0 - Support for [email protected]. Node v8.x.x, v9.x.x are no longer supported (use v1.4.7 of the lib)

Supported versions

  • node.js: 10.x, 12.x, 14.x
  • mongoose: 5.x, 6.x
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].