npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-schema-jsonschema-x

v1.1.3

Published

Mongoose extention that allows to build json schema for mongoose models, schemas and queries

Downloads

2

Readme

Build status Coverage Status

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

Samples

Let's build json schema from simple mongoose schema

'use strict';

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}
});

let jsonSchema = BookSchema.jsonSchema();

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

Output:

{
  type: 'object',
  properties: {
    title: { type: 'string' },
    year: { type: 'number' },
    author: { type: 'string' },
    _id: { type: 'string', format: 'uuid', 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

'use strict';

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', format: 'uuid', 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', format: 'uuid', pattern: '^[0-9a-fA-F]{24}$' },
        __v: { type: 'number' }
      },
      required: [ 'firstName', 'lastName' ],
      'x-ref': 'Person',
      description: 'Refers to Person'
    },
    _id: { type: 'string', format: 'uuid', pattern: '^[0-9a-fA-F]{24}$' },
    __v: { type: 'number' }
  },
  required: [ 'title', 'author' ]
}
'use strict';

const extendMongooose = require('mongoose-schema-jsonschema');
const mongoose = extendMongooose(require('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 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', format: 'uuid', pattern: '^[0-9a-fA-F]{24}$' }
    }
  },
  maxItems: 5
}

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):
  var jsonSchema = mongoose.SchemaType.prototype.jsonSchema.call(this);

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

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

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

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

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

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

   return jsonSchema;
}

Command line

There is a command line utility to build schema without importing mongoose-schema-jsonschema to your project

npm i -g jsonschema-builder

Usage

Getting options:

jsonschema-builder --help

Output:

  Usage: jsonschema-builder [options] <pathToModels>

  Options:

    -h, --help     output usage information
    -V, --version  output the version number
    -j, --json     JSON format for output
    -n, --noid     Removes id field from resulting schema

Samples and other details can be reached by the link: jsonschema-builder