Mould.js

Define Schema on Database level.

Document validation has been introduced to MongoDb since version 3.2 . Before that, we could only define schema on application level. With Mould.js, we could define schema easily on database level, which means you could apply or modify the schema rule to collections as the bootstrap step of your application. After that, the validation is connection or application independent, the document will always be validated first whenever it is inserted or modified.

Differences between Mould.js and Mongoose

Feature Mongoose Mould.js
Schema Level Application Database
Features Full Minimal

Get Started with Database Level Schema Validation

Attention: mongodb version >= 3.2 required

npm install mouldjs --save
let Mould = require('mouldjs')
let User = new Mould({
    name  : {$type: 'string', $exists: true},
    age   : {$type: 'int', $lt: 200},
    email : {$regex: \"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"\}
    sex   : {$in: ['male','female','unknown']}
});

check full schema lists.

//with promise
User.applyTo(db, collection)
    .then(...)
    .catch(...);

api docs


Api

Class Mould Constructor

.applyTo(db, collection)

Apply the Mould to specified collection of db. db is an instance of node-mongodb-native-driver Db class. If the collection is not found in the db, the method will create collection for you, then apply the mould. If the collection is existed and already has some data, the method will success as well. But later on, any data inserted will be tested against the Schema.

Parameters:

Return:

Return a Promise contains information which indicates whether the application is succeeded or failed.

example

.setValidationLevel

.setValidationAction

static checkCollectionExists

static getCollectionValidator

static isMongoVersionSupport

Examples

Check the examples folder

Types

Types: https://docs.mongodb.org/v3.2/reference/operator/query/type/#document-type-available-types

Validators

Validator: https://docs.mongodb.org/v3.2/core/document-validation/


TODO