• Stars
    star
    147
  • Rank 251,347 (Top 5 %)
  • Language
    JavaScript
  • Created about 14 years ago
  • Updated about 12 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flexible non-magical layer for the nodejs MongoDB driver
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 = require('mongolia').model(db, 'users');

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 = require('mongodb/lib/mongodb/db').Db,
    Server = require('mongodb/lib/mongodb/connection').Server,
    db = new Db('blog', new Server('localhost', 27017, {auto_reconnect: true, native_parser: true}));

db.open(function () {
  var User = require('./user.js')(db);

  User.mongo('findOne', {name: 'foo'}, console.log);
  User.mongo({method: 'insert', hooks: false}, {name: 'foo'}, console.log);
});

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.findOne({name: 'foo'}, console.log);
  User.insert({name: 'foo'}); // 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 = require('mongolia').model(db, 'users');

USER.namespaces = {
  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.mongo('insert:public', {account: {email: '[email protected]'}, password: 'fleiba', credit_card_number: 123, is_active: true});
// insert => {account: {email: '[email protected]'}}

USER.validateAndUpdate({account: {email: '[email protected]'}}, {'$set': {'account.email': '[email protected]', password: '123'}, {namespace: 'public'});
// updates => {'$set': {'account.email': '[email protected]'}}

USER.mongo('findArray:public', {account: {email: '[email protected]'}});
// find => {account: {email: '[email protected]', name: 'paco'}}

USER.mongo('findArray:accounting', {account: {email: '[email protected]'}});
// find => {account: {email: '[email protected]', name: 'paco'}, password: 'fleiba', credit_card_number: 123}

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 = require('mongolia').model(db, 'users');

USER.maps = {
  _id: ObjectID,
  account: {
    email: String,
    name: function (val) {val.toUpperCase()}
  },
  password: String,
  salt: String,
  is_deleted: Boolean
};

USER.mongo('insert', {email: '[email protected]', password: 123, name: 'john', is_deleted: 'true'});
// 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 an insert.

  • afterInsert(documents, callback): triggered after an `insert.

  • beforeUpdate(query, update, callback): triggered before an update or findAndModify command.

  • afterUpdate(query, update, callback): triggered after an update or findAndModify command.

  • beforeRemove(query, callback): triggered before a remove command.

  • afterRemove(query, callback): triggered after a remove command.

Example:

var COMMENT = require('mongolia').model(db, 'comments'),
    Post = require('./post');

COMMENT.beforeInsert = function (documents, callback) {
  documents.forEach(function (doc) {
    doc.created_at = new Date();
  });
  callback(null, documents);
};

COMMENT.afterInsert = function (documents, callback) {
  documents.forEach(function (doc) {
    Post(db).mongo('update', {_id: doc.post._id}, {'$inc': {num_posts: 1}}); // fire and forget
  });
  callback(null, documents);
};

USER.mongo('insert', {email: '[email protected]'});
// stored => {email: '[email protected]', 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 = require('mongolia').model(db, 'posts');

// only embed the comment's _id, and title
POST.skeletons = {
  comment: ['_id', 'title', 'post.name']
};

var comment = {'_id': 1, title: 'foo', body: 'Lorem ipsum', post: {_id: 1, name: 'bar'}}
console.log(Post(db).getEmbeddedDocument('comment', comment));
// outputs => {'_id': 1, title: 'foo', post: {name: 'bar'}};

console.log(Post(db).getEmbeddedDocument('comment', comment, 'post'));
// outputs => {post: {'_id': 1, title: 'foo', post: {name: 'bar'}}};

console.log(Post(db).getEmbeddedDocument('comment', comment, 'posts', true));
// outputs => {'posts._id': 1, 'posts.title': 'foo', 'posts.post.name': 'bar'};

updateEmbeddedDocument

Updates an embed object following the skeletons directive.

Model.updateEmbeddedDocument(query, document_name, document[, options, callback]);

Example:

module.exports = function (db) {
  var USER = require('mongolia').model(db, 'users');

  // After updating a user, we want to update denormalized Post.author foreach post
  USER.afterUpdate = function (query, update, callback) {
    Post(db).updateEmbeddedDocument({_id: query._id}, 'author', update, {upsert: false}, callback);
  };

  return USER;
};

pushEmbeddedDocument

Pushes an embedded document following the skeletons directive.

Model.pushEmbeddedDocument(query, data, name[, options, callback]);

Example:

module.exports = function (db) {
  var POST = require('mongolia')(db, 'posts');

  // After inserting a post, we want to push it to `users.posts[]`
  POST.afterInsert = function (documents, callback) {
    User(db).pushEmbeddedDocument({_id: documents[0].author._id}, 'posts', document, callback);
  };

  return POST;
}

Create and update using validations

Mongolia provides two methods that allow you to create and update using the validator.

Model.validateAndInsert(document[, options, callback(error, validator)]);
Model.validateAndUpdate(document, update[, options, callback(error, validator)]);

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.

validate(query, update, callback);

Example:

// post.js
module.exports = function (db) {
  var POST = require('mongolia').model(db, 'posts');

  POST.validate = function (query, update, callback) {
    var validator = require('mongolia').validator(query, update);

    validator.validateRegex({
      title: [validator.regex.title, 'Incorrect title'],
      body: [/.{4,200}/, 'Incorrect body'],
    });

    if (!update.body === 'Lorem ipsum') {
      validator.addError('body', 'You can be a little bit more creative');
    }

    callback(null, validator);
  }

  return POST;
};

// app.js
var Post = require('./post.js');

Post(db).validateAndInsert(
  {title: 'This is a post', body: 'Lorem ipsum'},
  function (error, validator) {
    if (validator.hasErrors()) {
      console.log(validator.errors);
    } else {
      console.log(validator.updated_document);
    }
  }
);

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 = require('mongolia').validator({foo: 1}, {'$inc': {foo: 1}});

if (validator.updated_document.foo > 1) {
  validator.addError('foo', 'foo must be ONE');
}
console.log(validator.hasError('foo')); // => true

All the methods listed below accept dot_notation.

API

Returns true if the validator is handling an updateInstance operation.

isUpdating()

Returns true if the validator is handling an createInstance operation.

isInserting()

Returns true if the attributed changed

attrChanged(attr)

Adds an error to your validator. Accept dot notation to add nested errors.

addError(field, value)

Returns true if the attributed failed a validation. Accept dot notation to check nested errors.

hasError(field)

Returns true if any attributed failed a validation

hasErrors()

It fills your validator with errors if any of the elements are empty

validateExistence({
  attr: 'Error message'
, attr: ...
})

It fills your validator with errors if any of the elements fail the regex

validateRegex({
  attr: [/regex/, 'Error message']
, attr: ...
})

It fills your validator with errors if any of the elements fail the confirmation (good for passwords)

validateConfirmation({
  attr: ['confirmation_attr', 'Error message']
, attr: ...
})

It fills your validator with errors if any of the queries fail (good to avoid duplicated data)

validateQuery({
  attr: [Model, query, false, 'Error message']
, attr: ...
}, callback)

Example using some of the validator features:

var User = function (db) {
  var USER = require('mongolia').model(db, 'users');

  USER.validate = function (document, update, callback) {
    var validator = require('mongolia').validator(document, update)
      , updated_document = validator.updated_document;

    validator.validateRegex({
      name: [validator.regex.username, 'Incorrect name'],
      email: [validator.regex.email, 'Incorrect email'],
      password: [validator.regex.password, 'Incorrect password'],
      description: [validator.regex.description, 'Incorrect description']
    });

    if (validator.attrChanged('password')) {
      validator.validateConfirmation({
        'password': ['password_confirmation', 'Passwords must match']
      });
    }

    if (!updated_document.tags || updated_document.tags.length <= 0) {
      validator.addError('tags', 'Select at least one tag');
    }

    validator.validateQuery({
      email: [
        this
      , {_id: {'$not': document._id}, email: updated_document.email}
      , false
      , 'There is already a user with this email'
      ]
    }, function () {
      callback(null, 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 <[email protected]>

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.

More Repositories

1

mobx-rest

REST conventions for Mobx
TypeScript
187
star
2

Backbone.Rel

Backbone.Rel extends your Backbone models with a lightweight relationships manager.
JavaScript
144
star
3

dialect

Translations for nodejs
JavaScript
109
star
4

testosterone

Virile testing for http servers or any nodejs application.
JavaScript
82
star
5

whatajong

Open source multiplayer mahjong using HTML5 and nodejs + socket.io
JavaScript
77
star
6

Backbone.Subset

Provides a collection-like constructor that allows you create a collection that is subset from a parent one
JavaScript
75
star
7

facebook-js

Easy peasy facebook client for connect
JavaScript
63
star
8

linkedin-js

Easy peasy linkedin client for connect
JavaScript
43
star
9

tldextract

Extract domain, subdomain and tld from a url
JavaScript
38
star
10

connect-i18n

Middleware for connect to handle i18n
JavaScript
25
star
11

dialect-http

http client to manage your dialect translations
JavaScript
25
star
12

asereje

Forget about assets builds
JavaScript
23
star
13

twitter-js

Easy peasy twitter client for connect
JavaScript
23
star
14

Backbone.Aggregator

Provides a collection-like constructor that allows you create aggregators from different collections
JavaScript
19
star
15

funk

Asynchronous functions made funky!
JavaScript
17
star
16

express-dialect

Pluggable express app to handle i18n and L18n
JavaScript
16
star
17

transsiberian

nodejs boilerplate built upon Express and Mongolia
JavaScript
15
star
18

i-love-async

"Slides" from the little talk I gave on the Barcelona nodejs meetup
JavaScript
14
star
19

resting-ducks

REST conventions for single stores
JavaScript
11
star
20

node-brainfuck

Brainfuck interpreter for nodejs
JavaScript
10
star
21

mobx-rest-fetch-adapter

Fetch adapter for mobx-rest
JavaScript
9
star
22

backbone.partial-fetch

Allows you to do smart partial fetching
JavaScript
9
star
23

backbone.middleware

Backbone.middleware
JavaScript
9
star
24

jasmine-prototype

prototype matchers and fixture loader for Jasmine framework
JavaScript
8
star
25

paginate-js

Paginate whatever you want, client and server side
JavaScript
6
star
26

screamcasts

Stream GIFS like a boss
JavaScript
6
star
27

mobx-rest-example

Example project built with mobx-rest
JavaScript
4
star
28

php_mongo

Tiny wrapper of the php mongo client
4
star
29

haskell-socket.io

Implementation of the socket-io protocol
Haskell
3
star
30

j

The smallest testing library in nodejs
JavaScript
3
star
31

miniMarkdown

An easy to extend parser for a subset of markdown
JavaScript
3
star
32

crawlr

Grab content and let people vote it
Ruby
3
star
33

backbone-example

a backbone + nodejs example
3
star
34

dotfiles

Vim files
Vim Script
2
star
35

js-styler

A simple functionto do all kind of CSS styling in JS. Works great with React!
JavaScript
2
star
36

underscore.inflection

Better underscore inflection module
JavaScript
2
star
37

you-call-me-maybe

Painless maybe monad for ruby
Ruby
1
star
38

mobx-rest-jquery-adapter

jQuery adapter for mobx-rest
JavaScript
1
star
39

trimmer

Rack endpoint to make templates and i18n translations available in javascript
Ruby
1
star
40

hellog

Hellog is a centralized log server that supports different protocols.
JavaScript
1
star