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 🙏

© 2025 – Pkg Stats / Ryan Hefner

payapi-swagger-mongoose

v1.2.8

Published

Generate mongoose schemas and models from swagger documents with mongoose-encryption support

Readme

Travis Status

payapi-swagger-mongoose (original: swagger-mongoose)

Generate mongoose schemas and models from swagger documents. Support mongoose-encryption for encrypted fields.

PLEASE NOTE: All PayApi related changes have been published and pushed into the master_payapi-swagger-mongoose branch.

Usage

Simply pass your swagger document to the compile method, and then dynamically access the underlying mongoose models.

For encrypted fields, you may pass the encryption parameters for selected models which will use the mongoose-encryption module to do transparent application level encryption (TDE).

Please note that restrictions of mongoose-encryption apply, e.g. do not encrypt indexed fields or do not try to use mongoose.update() for encrypted fields.

var swaggerMongoose = require('payapi-swagger-mongoose');

var swagger = fs.readFileSync('./petstore.json');
var Pet = swaggerMongoose.compile(swagger).models.Pet;
var myPet = new Pet({
    id: 123,
    name: 'Fluffy'
    });
myPet.save();

Or with encryption enabled:

var swaggerMongoose = require('payapi-swagger-mongoose');

var swagger = fs.readFileSync('./petstore.json');
var Pet = swaggerMongoose.compile(swagger, null, {
  enc: 'YOUR_ENCRYPTION_KEY'
  sig: 'YOUR_SIGNING_KEY',
  encryptedSchemas: [
    {
      name: 'Pet',
      fields: ['name']
    }
  ]
}).models.Pet;
var myPet = new Pet({
    id: 123,
    name: 'Fluffy'
    });
myPet.save();

There are 3 different use cases and 3 new custom options available for the new x-swagger-mongoose custom property for Swagger documents that are v2 and greater.

Custom options include: schema-options, additional-properties, and exclude-schema

By default the exclude-schema option is set to false.

Global Schema Options

x-swagger-mongoose:
  schema-options:
    timestamps: true
definitions:
  User: ...

Per-Schema Options

  User:
    type: object
    x-swagger-mongoose:
      schema-options:
          timestamps: true

Unique Index at the property level

  Person:
    required:
      - login
    properties:
      _id:
        type: string
      login:
        type: string
        x-swagger-mongoose:
          index:
            unique: 'true'

Compound Indexes at the document level

definitions:
  House:
    x-swagger-mongoose:
      index:
        lng: 1
        lat: 1

Unique Compound Indexes at the document level

  User:
    type: object
    x-swagger-mongoose:
      index:
        firstName: 1
        lastName: 1
        unique: true

Swagger Validation requires String but Schema defined as a reference

  User:
    type: object
    properties:
      otherSchema:
        type: string
        x-swagger-mongoose:
          $ref: "#/definitions/OtherSchema"

Additional Mongo Schema paths that are not shown in Swagger-UI Documentation

  SchemaName:
    type: object
    x-swagger-mongoose:
      additional-properties:
        user:
          $ref: "#/definitions/User"
        approved:
          type: string
          format: datetime
        rejected:
          type: string
          format: datetime

No Mongo Schema created for this definition

  ExcludedSchema:
    type: object
    x-swagger-mongoose:
      exclude-schema: true

Custom validators

This is a bit of a work around, but in the top-level of your swagger doc:

x-swagger-mongoose:
  validators: ./lib/validators

validators is a relative path to the validators/index.js folder/file, FROM process.cwd().

each validator is an object, that contains two properties:

  • message: this is the text displayed in the mongoose error when it returns false
  • validator: this is the function that takes one argument (I believe) and returns true or false.

the properties must have these names, and must be exported in the index. unless you're aware of how to require an entire folder, in which case pull requests are welcome.

example validator:

//  /lib/validators/index.js
module.exports.homePhone = {
  message: '{VALUE} is not a valid home phone number!',
  validator: function(v){
    return /([0-9]{1}[-\.\s])?([\(\[]?[0-9]{3}[\)\]]?[-\.\s])?([0-9]{3})[-\.\s]([0-9]{4})(?:\s?(?:x|ext)\s?([0-9])+)?/.test(v)
  }
}

at the property that you want to attach a validator for, add the validator property and the name of the function.

phone:
  type: object
  properties:
    home:
      type: string
      x-swagger-mongoose:
        validator: homePhone
    mobile:
      type: string

Installation

npm install payapi-swagger-mongoose

Limitations

swagger-mongoose supports the following attributes: integer, long, float, double, string, password, boolean, date, dateTime, object, array (including nested schemas). swagger-mongoose also supports relationships between objects in a swagger document (thanks to @buchslava)

swagger-mongoose does not yet perform/create any validation from the swagger definitions (see issues if you'd like to help)

License

Copyright 2017 PayApi and other contributors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.