Mongorito Tcomb
Bring schema validation to Mongorito thanks to tcomb
Install
npm i -S mongorito-tcomb
Usage (ES6)
import co from 'co'
import Mongorito, {Model, t} from 'mongorito-tcomb'
class User extends Model {
get Schema() {
return t.struct({
name: t.unique(t.String),
surname: t.maybe(t.String)
});
}
}
class Post extends Model {
get Schema() {
return t.struct({
title: t.String,
content: t.String,
author: t.ID(User)
});
}
}
co(function *(val) {
yield Mongorito.connect('localhost/mongo-tcomb-playground');
yield User.remove()
var valid = new User({name: 'Valid'});
yield valid.save();
var invalid = new User({name: 'Invalid', surname: 88});
try {
yield invalid.save();
} catch (e) {
console.log(e);
}
var sameName = new User({name: 'Valid', surname: 'But not unique' });
try {
yield sameName.save();
} catch (e) {
console.log(e);
}
var post = new Post({
title: 'Hello',
content: 'Lorem Ipsum...',
author: "" + valid.get('_id')
});
yield post.save();
post.set('author', 'I want to be an ID...');
try {
yield post.save();
} catch (e) {
console.log(e);
}
post.set('author', '' + post.get('_id'));
try {
yield post.save();
} catch (e) {
console.log(e);
}
yield Mongorito.disconnect();
});
For coffeescript, you can see examples
API
Mixins
patch: (Model) -> PatchedModel
The patch function can be useful to combine different Mongorito plugins. It take a class,
extend it then return the extended class.
Customs tcomb types
t.unique
It ensure that the type is unique in the database.
Usage: t.unique(T)
where T is any tcomb type
t.ID
It represent the ID of an element in the database.
Usage: t.ID(M)
where M is a Mongorito model
It ensure that ID is valid and exist in the database
TODOS