mongoose-schema-model

Validation and formatting, converting MongooseDB schema definitions to be used in any environment

Usage no npm install needed!

<script type="module">
  import mongooseSchemaModel from 'https://cdn.skypack.dev/mongoose-schema-model';
</script>

README

mongoose-schema-model

browser support

Build Status

Small model definitions (MongooseDB style) for composable use in other environments.

  • Share the same model definitions from MongooseDB on the server with your client
  • Use to apply transformations getters/setters between client and REST API (casting form strings as numbers, etc.)
  • Shared validations in server/client

Install

Currently only in npm as commonjs.

npm install mongoose-schema-model

Usage

Using a Mongoose Schema definition, apply getter and setter transformations and validation.


// Declare a schema definition

var Model = require("mongoose-schema-model");

function numberCast (x) { return ~~x; }
function split (x) { return x.split(', '); }

var definitions = {
  year: { type: Number, min: 1900, max: 2014, set: numberCast },
  items: { type: [String], lowercase: true, get: split },

};

var model = Model(definitions);

// `get` applies the `get` transformation
model.get("items", ["hello", "world"]); // "hello, world"

// `set` applies all implicit and `set` transformations, as well as subsequently validating
// the model, post-transform.
var response = model.set("items", ["HELLO", "WORLD"]);
response.value; // `["hello", "world"]`, the implicit `lowercase` transform was applied to each element
response.error; // null

response = model.set("year", "2000"); 
response.value; // `2000`, transforms applied via `set`
response.error ; // null

response = model.set("year", "1550"); 
response.value; // `2000`, transforms applied, via `set`
response.error; // "Path `year` (1550) is less than the minimum allowed value (1900)."

Supported Types

  • Number
  • String
  • [Number]
  • [String]

Supported Properties

Transforms

Validations

License

MIT License