ooo ooooo oooo o8o
`88. .888' `888 `"'
888b d'888 .ooooo. ooo. .oo. .oooooooo .ooooo. 888 oooo .oooo.
8 Y88. .P 888 d88' `88b `888P"Y88b 888' `88b d88' `88b 888 `888 `P )88b
8 `888' 888 888 888 888 888 888 888 888 888 888 888 .oP"888
8 Y 888 888 888 888 888 `88bod8P' 888 888 888 888 d8( 888
o8o o888o `Y8bod8P' o888o o888o `8oooooo. `Y8bod8P' o888o o888o `Y888""8o
d" YD
"Y88888P'
Mongolia is a thin layer that sits on top of the mongo native driver and helps you dealing with your data logic. Mongolia is not an ORM. Models contains no state, just logic. Mongolia contains no magic.
Install
npm install mongolia
Mongolia contains two independent modules:
model
: An object representing a collection with some hooks of mongo calls.validator
: An object that validates mongoDB documents and returns errors if found.
Model
Models are attached to collections. Models don't map data from the db, they just define the logic.
var USER = ;
mongo proxied collection commands
Calls to the db are done using the method mongo
.
mongo
proxies all the collection
methods defined on the driver plus some custom methods.
This allows mongolia to extend the driver with extra functionalties:
- Namespacing: Allows you to filter the documents going and coming from the db.
- Mapping: Allows you to apply functions to the documents attributes going and coming from the db.
- Hooks: They are triggered before and after a call is done.
There are two APIs:
mongo('method[:namespace]', args)
and
mongo({method: method[, namespace: namespace, namespacing: false, mapping: false, hooks: false])
Example:
var Db = DbServer = Serverdb = 'blog' 'localhost' 27017 auto_reconnect: true native_parser: true;db;
All the collection
methods from the driver are supported and have a shortcut so you can use Mongolia
like the native driver (with the advantage of not having to ask for the collection):
Example:
User;User; // fire and forget});
If you need more information on collection methods visit the driver documentation
Custom mongo collection commands
Mongolia provides some useful commands that are not available using the driver.
findArray
: find that returns an array instead of a cursor.mapReduceArray
: mapReduce that returns an array with the results.mapReduceCursor
: mapReduce that returns a cursor.
Namespacing
Secure your data access defining visibility namespaces.
You can namespace a call to the database by appending :namespace
on
your proxied method.
If called without a namespace, the method will work ignoring the namespace
directives.
You can extend
other namespaces and add
or remove
some data visibility.
var USER = ;USERnamespaces =public: 'account.email' 'account.name' '_id'private:extend: 'public'add: 'password'accounting:extend: 'private'add: 'credit_card_number' // don't do this at home;USER;// insert => {account: {email: 'foo@bar.com'}}USER
Use this feature wisely to filter data coming from forms.
Mappings and type casting
Mongolia maps
allows you to cast the data before is stored to the database.
Mongolia will apply the specified function for each attribute on the maps
object.
By default we provide the map _id -> ObjectId
, so you don't need to cast it.
var USER = ;USERmaps =_id: ObjectIDaccount:email: String{val}password: Stringsalt: Stringis_deleted: Boolean;USER;// stored => {password: '123', name: 'JOHN', is_deleted: true}
Hooks
Mongolia let you define some hooks on your models that will be triggered after a mongoDB command.
-
beforeInsert(documents, callback)
: triggered before aninsert
. -
afterInsert(documents, callback)
: triggered after an `insert. -
beforeUpdate(query, update, callback)
: triggered before anupdate
orfindAndModify
command. -
afterUpdate(query, update, callback)
: triggered after anupdate
orfindAndModify
command. -
beforeRemove(query, callback)
: triggered before aremove
command. -
afterRemove(query, callback)
: triggered after aremove
command.
Example:
var COMMENT =Post = ;COMMENT {documents;;};COMMENT {documents;;};USER;// stored => {email: 'foo@bar.com', created_at: Thu, 14 Jul 2011 12:13:39 GMT}// Post#num_posts is increased
Embedded documents
Mongolia helps you to denormalize your mongo collections.
getEmbeddedDocument
Filters document following the skeletons
attribute.
getEmbeddedDocument(name, object, scope [, dot_notation]);
Example:
var POST = ;// only embed the comment's _id, and titlePOSTskeletons =comment: '_id' 'title' 'post.name';var comment = '_id': 1 title: 'foo' body: 'Lorem ipsum' post: _id: 1 name: 'bar'console;// outputs => {'_id': 1, title: 'foo', post: {name: 'bar'}};console;// outputs => {post: {'_id': 1, title: 'foo', post: {name: 'bar'}}};console;// outputs => {'posts._id': 1, 'posts.title': 'foo', 'posts.post.name': 'bar'};
updateEmbeddedDocument
Updates an embed object following the skeletons
directive.
Model;
Example:
module {var USER = ;// After updating a user, we want to update denormalized Post.author foreach postUSER {;};return USER;};
pushEmbeddedDocument
Pushes an embedded document following the skeletons
directive.
Model;
Example:
module {var POST = db 'posts';// After inserting a post, we want to push it to `users.posts[]`POST {;};return POST;}
Create and update using validations
Mongolia provides two methods that allow you to create and update using the validator
.
Model;Model;
To scope the insert/update within a namespace, use options.namespace
.
In order to validate an insertion/update, the model have to implement a validate
function on your model.
;
Example:
// post.jsmodule {var POST = ;POST {var validator = ;validator;if !updatebody === 'Lorem ipsum'validator;;}return POST;};// app.jsvar Post = ;;
Validator
Mongolia validator accepts a document and an update.
If you are validating an insert, the document will be an empty object {}
and the update
the document you are inserting.
Mongolia will resolve the update client side exposing a updated_document
.
var validator = ;if validatorupdated_documentfoo > 1validator;console; // => true
All the methods listed below accept dot_notation
.
API
Returns true if the validator is handling an updateInstance operation.
Returns true if the validator is handling an createInstance operation.
Returns true if the attributed changed
Adds an error to your validator. Accept dot notation to add nested errors.
Returns true if the attributed failed a validation. Accept dot notation to check nested errors.
Returns true if any attributed failed a validation
It fills your validator with errors if any of the elements are empty
It fills your validator with errors if any of the elements fail the regex
It fills your validator with errors if any of the elements fail the confirmation (good for passwords)
It fills your validator with errors if any of the queries fail (good to avoid duplicated data)
Example using some of the validator features:
var {var USER = ;USER {var validator =updated_document = validatorupdated_document;validator;if validatorvalidator;if !updated_documenttags || updated_documenttagslength <= 0validator;validator;}return USER;};
Tests
Mongolia is fully tested using mocha To run the tests use:
make
Example
Mongolia has a fully working blog example on the example
folder.
Contributors
In no specific order.
License
(The MIT License)
Copyright (c) 2010-2011 Pau Ramon Revilla <masylum@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.