mjs

mongo-json-schema

This is a library for validating objects against a jsonSchema before inserting into (and after retrieving from) mongo.

Showing:

Popularity

Downloads/wk

4

GitHub Stars

8

Maintenance

Last Commit

6yrs ago

Contributors

1

Package

Dependencies

5

Size (min+gzip)

73.6KB

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

Readme

#mongo-json-schema

This is a library for validating objects against a jsonSchema before inserting into (and after retrieving from) mongo.

Creating a schema object

var Schema = require('mongo-json-schema');
var schema = Schema({
  nested: {
    type: 'object',
    properties: {
      sub: {
        type: "objectid"
      }
    }
  },
  count: {
    type: "number",
    required: false
  },
  participants: {
    type: "array",
    items: {
      type: "objectid",
    }
  }
});
  

Validating an input object

schema.validate({
  _id '52f044dee2896a8264d7ec2f',
  nested: {
      sub: '52f044dee2896a8264d7ec2f'
  }
})
// throws errors if its not valid!

Getting a standard jsonSchema

schema.getJsonSchema();

returns:

{
  {
    type: 'object',
    properties: {
      _id: {
        type: "string",
        pattern: "^[a-fA-F0-9]{24}$",
        required: true
      },
      nested: {
        type: 'object',
        properties: {
          sub: {
            type: "string",
            pattern: "^[a-fA-F0-9]{24}$",
          }
        }
      },
      count: {
        type: "number",
        required: false
      },
      participants: {
        type: "array",
        items: {
          type: "string",
          pattern: "^[a-fA-F0-9]{24}$"
        }
      }
    }
  }
}

###getting an object with strings for ids

  schema.idsToStrings({
    _id: ObjectID('52f044dee2896a8264d7ec2f'),
    nested: {
      sub: ObjectID('52f044dee2896a8264d7ec2f'),
    },
    count: 42,
    participants: [ObjectID('52f044dee2896a8264d7ec2f'),ObjectID('52f044dee2896a8264d7ec2f')]
  });

returns:

{
  _id: '52f044dee2896a8264d7ec2f',
  nested: {
    sub: '52f044dee2896a8264d7ec2f',
  },
  count: 42,
  participants: ['52f044dee2896a8264d7ec2f','52f044dee2896a8264d7ec2f']
}

###getting an object with ObjectIDs for ids

schema.stringsToIds({
  _id: '52f044dee2896a8264d7ec2f',
  nested: {
    sub: '52f044dee2896a8264d7ec2f',
  },
  count: 42,
  participants: ['52f044dee2896a8264d7ec2f','52f044dee2896a8264d7ec2f']
});

returns:

{
  _id: ObjectID('52f044dee2896a8264d7ec2f'),
  nested: {
    sub: ObjectID('52f044dee2896a8264d7ec2f'),
  },
  count: 42,
  participants: [ObjectID('52f044dee2896a8264d7ec2f'),ObjectID('52f044dee2896a8264d7ec2f')]
}

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial