Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Merge branch 'master' of git@github.com:masylum/mongolia

  • Loading branch information...
commit c6884fd344cd48c3033a3a6e32913172320c7232 2 parents 1993f6f + 321bada
Pau Ramon Revilla masylum authored

Showing 1 changed file with 87 additions and 75 deletions. Show diff stats Hide diff stats

  1. +87 75 README.md
162 README.md
Source Rendered
@@ -19,8 +19,8 @@ No magic, no pain.
19 19
20 20 Mongolia contains two independent modules:
21 21
22   - * Model: An object representing a collection with some wrappers/hooks of MongoDB calls.
23   - * Validator: An object that validates MongoDB documents and returns errors if found.
  22 + * `Model`: An object representing a collection with some wrappers/hooks of MongoDB calls.
  23 + * `Validator`: An object that validates MongoDB documents and returns errors if found.
24 24
25 25 # Model
26 26
@@ -28,141 +28,160 @@ Each model has a colection name and a reference to the database.
28 28
29 29 Models don't map data from MongoDB, they are just a layer to centralize all the logic.
30 30
31   - var Model = require('model');
32   -
33 31 var User = function (db) {
34   - var user = Model(db, 'users');
  32 + // our user model will do MongoDB calls using 'users' collection
  33 + var USER = require('mongolia').model(db, 'users');
35 34
36 35 // implement some user logic
37 36
38   - return user;
  37 + return USER;
39 38 };
40 39
41   -Calls to the database are done using the function mongoCall.
  40 +## MongoDB commands
  41 +
  42 +Calls to the database are done using the function `mongoCall`.
  43 +
  44 + var Db = require('mongodb/lib/mongodb/db').Db,
  45 + Server = require('mongodb/lib/mongodb/connection').Server,
  46 + db = new Db('blog', new Server('localhost', 27017, {auto_reconnect: true, native_parser: true}));
42 47
43   - var User = User(db);
44   - User.mongoCall('function', args, callback);
  48 + db.open(function () {
  49 + var User = require('./user.js')(db);
  50 + User.mongoCall('find', {name: 'foo'}, function (error, user) {
  51 + console.log(user);
  52 + });
  53 + });
45 54
46 55 All the collection.js functions from the driver are supported.
47   -If you need more information visit the official driver http://github.com/christkv/node-mongodb-native.
48 56
49   -## Custom MongoDB functions
  57 +If you need more information visit the [official driver](http://github.com/christkv/node-mongodb-native) documentation
50 58
51   - * findArray: find + toArray.
52   - * mapReduceArray: mapReduce that returns an array with the results.
53   - * mapReduceCursor: mapReduce that returns a cursor.
  59 +## Custom MongoDB commands
54 60
55   -## Wrapped functions with hooks
  61 +Mongolia provides some useful commands that are not available using the driver.
56 62
57   - * insert: triggers onCreate and afterCreate hooks.
58   - * update: triggers onUpdate and afterUpdate hooks.
59   - * findAndModify: triggers onUpdate and afterUpdate hooks.
  63 + * `findArray`: find that returns an array instead of a cursor.
  64 + * `mapReduceArray`: mapReduce that returns an array with the results.
  65 + * `mapReduceCursor`: mapReduce that returns a cursor.
  66 +
  67 +## Hooks
  68 +
  69 +Mongolia let you define some hooks on your models that will be triggered after a MongoDB command.
  70 +
  71 + * `onCreate(element)`: triggered *before* an `insert`. If multiples elements are inserted, it will be called for each of them.
  72 + * `afterCreate(element)`: triggered *after* an `insert. If multiples elements are inserted, it will be called for each of them.
  73 + * `onUpdate(update)`: triggered *before* an `update` or `findAndModify` command.
  74 + * `afterUpdate(update)`: triggered *after* an `update` or `findAndModify` command. // Not yet implemented!
60 75
61 76 Example:
62 77
63 78 var Comment = function (db) {
64   - var comment = Model(db, 'comments');
  79 + var COMMENT = require('mongolia').model(db, 'comments');
65 80
66   - comment.onCreate = function (element) {
  81 + COMMENT.onCreate = function (element) {
67 82 element.created_at = new Date();
68 83 };
69 84
70   - comment.atferCreate = function (element) {
  85 + COMMENT.atferCreate = function (element) {
71 86 var post = require('./models/post')(this.db);
72 87 post.mongoCall('update', {_id: element.post_id}, {'$inc': {num_posts: 1}});
73 88 };
74 89
75   - return comment;
  90 + return COMMENT;
76 91 };
77 92
78   -## Working with embedded documents
  93 +## Embedded documents
79 94
80   -Mongolia helps you to denormalizing your MongoDB database.
81   -You can define _skeletons_ for your embedded documents.
82   -Those _skeletons_ define which data do you want to denormalize.
  95 +Mongolia helps you to denormalize your MongoDB database.
83 96
84 97 ### setEmbedObject
85   -Returns a denormalized and filtered embed object.
  98 +
  99 +Filters an embed object following the `skeletons` directive.
86 100
87 101 setEmbedObject(name, object);
88 102
89 103 Example:
90 104
91 105 var Post = function (db) {
92   - var post = Model(db, 'posts');
  106 + var POST = require('mongolia').model(db, 'posts');
93 107
94   - // only embed the comment's title
95   - post.skeletons= {
  108 + // only embed the comment's _id, and title
  109 + POST.skeletons= {
96 110 comment: ['_id', 'title']
97 111 };
98 112
99   - return post;
  113 + return POST;
100 114 };
101 115
102 116 var comment = {'_id': 1, title: 'foo', body: 'Lorem ipsum'}
103 117 Post(db).setEmbedObject('comment', comment) // => {'_id': 1, title: 'foo'};
104 118
105 119 ### updateEmbedObject
106   -Updates an embed object. Plays really well with the update hooks.
  120 +
  121 +Updates an embed object.
107 122
108 123 updateEmbedObject(model, data, name, options, callback);
109 124
110 125 Example:
111 126
112   - var Post = function (db) {
113   - var post = Model(db, 'posts');
  127 + var User = function (db) {
  128 + var USER = require('mongolia').model(db, 'users');
114 129
115   - post.afterUpdate = function (element, update) {
116   - Author(db).updateEmbedObject(element, update, 'post', null, function (error, doc) {
117   - // Author.post updated!
  130 + // After updating a user, we want to update denormalized Post.author foreach post
  131 + USER.afterUpdate = function (element, update) {
  132 + Post(db).updateEmbedObject(element, update, 'author', null, function (error, docs) {
  133 + console.log(docs);
118 134 });
119 135 };
120 136
121   - return post;
  137 + return USER;
122 138 };
123 139
124 140 ### pushEmbedObject
125   -Pushes an embed object. Plays really well with the insert hooks.
  141 +
  142 +Pushes an embed object.
126 143
127 144 pushEmbedObject(model, data, name, options, callback);
128 145
129 146 Example:
130 147
131 148 var Post = function (db) {
132   - var post = Model(db, 'posts');
  149 + var POST = require('mongolia')(db, 'posts');
133 150
134   - post.afterInsert = function (element) {
135   - Author(db).pushEmbedObject(element.author, update, 'posts', null, function (error, doc) {
136   - // Author.posts[] now contains this post
  151 + POST.afterCreate = function (element) {
  152 + User(db).pushEmbedObject(element.author, element, 'posts', null, function (error, doc) {
  153 + // User.posts[] now contains this post
137 154 });
138 155 };
139 156
140   - return post;
  157 + return POST;
141 158 }
142 159
143 160
144 161 ## Create and update instances
145 162
146 163 Mongolia provides with two methods that allow you to create and update using the Validator.
  164 +
147 165 Its important to notice that createInstance and updateInstance are asynchronous methods as some validations may require database call.
148 166
149 167 createInstance(element, callback);
150 168 updateInstance(element, update, callback);
151 169
152 170 The callback returns _error_, and a _validator_ object.
153   -Those two methods trigger onCreateInstance/onUpdateInstance, asynchronously.
154 171
155   -In order to validate an insertion/update, the model have to implement a _validate_ function.
  172 +Those two methods trigger onCreateInstance/onUpdateInstance, asynchronously. [this will be deprecated and replaced with async onCreate and onUpdate soon]
  173 +
  174 +In order to validate an insertion/update, the model have to implement a _validate_ function on your model.
156 175
157 176 validate(element, update, callback);
158 177
159 178 Example:
160 179
161 180 var Post = function (db) {
162   - var post = Model(db, 'posts');
  181 + var POST = require('mongolia').model(db, 'posts');
163 182
164   - post.validate = function (element, update, callback) {
165   - var validator = require('./validator');
  183 + POST.validate = function (element, update, callback) {
  184 + var validator = require('mongolia').validator(element, data);
166 185
167 186 validator.validateRegex({
168 187 title: [validator.regex.title, 'Incorrect title'],
@@ -175,75 +194,68 @@ Example:
175 194 callback(null, validator);
176 195 }
177 196
178   - return post;
  197 + return POST;
179 198 };
180 199
181 200 var post = {title: 'This is a post', body: 'Lorem ipsum'};
182   - var Post = Post(db);
183 201
184   - Post.createInstance(post, function (error, validator) {
  202 + Post(db).createInstance(post, function (error, validator) {
185 203 if (validator.hasErrors()) {
186   - res.render('/posts/new', {
187   - locals: {
188   - title: 'New Post',
189   - post: validator.updated_model,
190   - validator: validator
191   - }
192   - });
  204 + console.log(validator.errors);
193 205 } else {
194   - res.redirect('/posts/' + validator.updated_model._id.toHexString());
  206 + console.log(validator.updated_model);
195 207 }
196 208 });
197 209
198 210 # Validator
199 211
200   -Returns true if the validator is handling an updateInstance operation.
201   -
202 212 isUpdating()
203 213
204   -Returns true if the validator is handling an createInstance operation.
  214 +Returns true if the validator is handling an updateInstance operation.
205 215
206 216 isInserting()
207 217
208   -Returns true if the attributed changed
  218 +Returns true if the validator is handling an createInstance operation.
209 219
210 220 attrChanged(attr)
211 221
212   -Adds an error to your validator. Accept dot notation to add nested errors.
  222 +Returns true if the attributed changed
213 223
214 224 addError(field, value)
215 225
216   -Returns true if the attributed failed a validation. Accept dot notation to check nested errors.
  226 +Adds an error to your validator. Accept dot notation to add nested errors.
217 227
218 228 hasError(field)
219 229
220   -Returns true if any attributed failed a validation
  230 +Returns true if the attributed failed a validation. Accept dot notation to check nested errors.
221 231
222 232 hasErrors()
223 233
224   -It fills your validator with errors if any of the elements are empty
  234 +Returns true if any attributed failed a validation
225 235
226 236 validateExistence(validations)
227 237
228   -It fills your validator with errors if any of the elements fail the regex
  238 +It fills your validator with errors if any of the elements are empty
229 239
230 240 validateRegex(validations)
231 241
232   -It fills your validator with errors if any of the elements fail the confirmation (good for passwords)
  242 +It fills your validator with errors if any of the elements fail the regex
233 243
234 244 validateConfirmation(validations)
235 245
236   -It fills your validator with errors if any of the queries fail (good to avoid duplicated data)
  246 +It fills your validator with errors if any of the elements fail the confirmation (good for passwords)
237 247
238 248 validateQuery(validations, callback)
239 249
  250 +It fills your validator with errors if any of the queries fail (good to avoid duplicated data)
  251 +
240 252 Example using some of the validator features:
241 253
242 254 var User = function (db) {
243   - var user = Model(db, 'users');
  255 + var USER = require('mongolia').model(db, 'users');
244 256
245   - user.validate = function (user, data, callback) {
246   - var validator = $.model('validator', [user, data]);
  257 + USER.validate = function (element, data, callback) {
  258 + var validator = require('mongolia').validator(element, data);
247 259
248 260 validator.validateRegex({
249 261 name: [validator.regex.username, 'Incorrect name'],
@@ -274,5 +286,5 @@ Example using some of the validator features:
274 286 }
275 287 }
276 288
277   - return user;
  289 + return USER;
278 290 };

0 comments on commit c6884fd

Please sign in to comment.
Something went wrong with that request. Please try again.