Permalink
Browse files

new way of finding documents, cleaner API, new examples, README.md

  • Loading branch information...
1 parent da900c7 commit 417d05a71b7db52647fa6b6b69b86d9fc4821f7f @vdemedes committed Mar 29, 2012
View
12 Readme.md
@@ -22,8 +22,8 @@ npm install mongorito
```coffee-script
Mongorito = require 'mongorito'
-Mongorito.connect 'database', ['127.0.0.1:27017'], 'user', 'password'
-Mongorito.cache ['127.0.0.1:11211'] # optional, allows automatic, smart caching. It is just one line to enable it!
+Mongorito.connect ['mongo://user:password@127.0.0.1:27017/databaseName']
+Mongorito.cache ['127.0.0.1:11211'] # optional, allows automatic caching. It is just one line to enable it!
class Post
constructor: ->
@@ -44,7 +44,7 @@ post.save (err) ->
post.remove ->
# removed!
-Post.find { title : 'Some title!' }, (err, posts) ->
+Post.find title : 'Some title!', (err, posts) ->
for post in posts
# post is an instance of Post model, so you can perform usual methods on it
post.remove ->
@@ -56,12 +56,12 @@ Check out **examples** folder, it has a lot of code, which describes all parts o
# For pure JS folks
-Nothing special, you will just have to use dirtier syntax, but that's ok.
+Honestly, Mongorito was not developed with "JS" in mind. Mongorito is for CoffeeScript developers. But, in case you have no other choice:
```javascript
var Mongorito = require('mongorito');
-Mongorito.connect('database', ['127.0.0.1:27017'], 'user', 'password');
+Mongorito.connect(['mongo://user:password@127.0.0.1:27017/databaseName']);
Mongorito.cache(['127.0.0.1:11211']);
var Post = (function(){
@@ -99,7 +99,7 @@ Post.find(function(err, posts){
Tests made using Mocha. Run using:
```
-cd tests && mocha *
+mocha
```
View
3 examples/connection.coffee
@@ -1,3 +1,4 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
+Mongorito.disconnect()
View
4 examples/connection.js
@@ -2,4 +2,6 @@ var Mongorito;
Mongorito = require('../lib/mongorito');
-Mongorito.connect('databaseName', ['127.0.0.1:27017']);
+Mongorito.connect(['mongo://127.0.0.1:27017/databaseName']);
+
+Mongorito.disconnect();
View
2 examples/definition.coffee
@@ -1,6 +1,6 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
class Post
constructor: ->
View
2 examples/definition.js
@@ -2,7 +2,7 @@ var Mongorito, Post;
Mongorito = require('../lib/mongorito');
-Mongorito.connect('databaseName', ['127.0.0.1:27017']);
+Mongorito.connect(['mongo://127.0.0.1:27017/databaseName']);
Post = (function() {
View
2 examples/hooks.coffee
@@ -1,6 +1,6 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
class Post
constructor: ->
View
2 examples/hooks.js
@@ -2,7 +2,7 @@ var Mongorito, Post;
Mongorito = require('../lib/mongorito');
-Mongorito.connect('databaseName', ['127.0.0.1:27017']);
+Mongorito.connect(['mongo://127.0.0.1:27017/databaseName']);
Post = (function() {
View
2 examples/operations.coffee
@@ -1,6 +1,6 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
class Post
constructor: ->
View
2 examples/operations.js
@@ -2,7 +2,7 @@ var Mongorito, Post, post;
Mongorito = require('../lib/mongorito');
-Mongorito.connect('databaseName', ['127.0.0.1:27017']);
+Mongorito.connect(['mongo://127.0.0.1:27017/databaseName']);
Post = (function() {
View
20 examples/queries.coffee
@@ -1,6 +1,6 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
class Post
constructor: ->
@@ -12,20 +12,20 @@ Post.find (err, posts) ->
for post in posts
console.log post.title # post is a Post model, so you can perform all usual operations
-Post.find { title: 'Nice title!' }, (err, posts) ->
+Post.find title: 'Nice title!', (err, posts) ->
-Post.findWithLimit 5, (err, posts) -> # getting only first 5 posts
+Post.find limit: 5, (err, posts) -> # getting only first 5 posts
-Post.findWithLimit { author: 'Drew' }, 5, (err, posts) -> # getting only first 5 posts with author = Drew
+Post.find author: 'Drew', limit: 5, (err, posts) -> # getting only first 5 posts with author = Drew
-Post.findWithLimit 5, 2, (err, posts) -> # getting only 5 posts, skipping first 2
+Post.find limit: 5, skip: 2, (err, posts) -> # getting only 5 posts, skipping first 2
-Post.findWithLimit { author: 'Drew' }, 5, 2, (err, posts) -> # getting only 5 posts, skipping first 2, with author = Drew
+Post.find author: 'Drew', limit: 5, skip: 2, (err, posts) -> # getting only 5 posts, skipping first 2, with author = Drew
-Post.findWithOrder { _id: -1 }, (err, posts) -> # getting posts, sorted by _id
+Post.find sort: _id: -1 (err, posts) -> # getting posts, sorted by _id
-Post.findWithOrderAndLimit { _id: -1 }, 5, (err, posts) -> # getting first 5 posts, sorted by _id
+Post.find limit: 5, sort: _id: -1, (err, posts) -> # getting first 5 posts, sorted by _id
-Post.findWithOrderAndLimit { _id: -1 }, 5, 2, (err, posts) -> # getting 5 posts, skipping first 2, sorted by _id
+Post.find limit: 5, skip: 2, sort: _id: -1, (err, posts) -> # getting 5 posts, skipping first 2, sorted by _id
-Post.findWithOrderAndLimit { author: 'Drew' }, { _id: -1 }, 5, 2, (err, posts) -> # getting 5 posts, skipping first 2, sorted by _id, with author = Drew
+Post.find limit: 5, skip: 2, author: 'Drew', sort: _id: -1, (err, posts) -> # getting 5 posts, skipping first 2, sorted by _id, with author = Drew
View
2 examples/validations.coffee
@@ -1,6 +1,6 @@
Mongorito = require '../lib/mongorito'
-Mongorito.connect 'databaseName', ['127.0.0.1:27017']
+Mongorito.connect ['mongo://127.0.0.1:27017/databaseName']
class Tweet
constructor: ->
View
2 examples/validations.js
@@ -2,7 +2,7 @@ var Mongorito, Tweet, tweet;
Mongorito = require('../lib/mongorito');
-Mongorito.connect('databaseName', ['127.0.0.1:27017']);
+Mongorito.connect(['mongo://127.0.0.1:27017/databaseName']);
Tweet = (function() {
View
316 lib/mongorito.coffee
@@ -1,54 +1,11 @@
mongolian = require 'mongolian'
async = require 'async'
memcacher = require 'memcacher'
+inflect = require 'i'
Client = undefined
Cache = undefined
-`String.prototype.plural = function() {
- var s = this.trim().toLowerCase();
- end = s.substr(-1);
- if(end == 'y') {
- var vowels = ['a', 'e', 'i', 'o', 'u'];
- s = s.substr(-2, 1) in vowels ? s + 's' : s.substr(0, s.length-1) + 'ies';
- } else if(end == 'h') {
- s += s.substr(-2) == 'ch' || s.substr(-2) == 'sh' ? 'es' : 's';
- } else if(end == 's') {
- s += 'es';
- } else {
- s += 's';
- }
- return s;
-}
-
-String.prototype.singular = function() {
- var s = this.trim().toLowerCase();
- var end = s.substr(-3);
- if(end == 'ies') {
- s = s.substr(0, s.length-3) + 'y';
- } else if(end == 'ses') {
- s = s.substr(0, s.length-2);
- } else {
- end = s.substr(-1);
- if(end == 's') {
- s = s.substr(0, s.length-1);
- }
- }
- return s;
-}
-
-String.prototype.camelize = function() {
- var s = 'x_' + this.trim().toLowerCase();
- s = s.replace(/[\s_]/g, ' ');
- s = s.replace(/^(.)|\s(.)/g, function($1) {
- return $1.toUpperCase();
- });
- return s.replace(/ /g, '').substr(1);
-}
-
-String.prototype.underscore = function() {
- return this.trim().toLowerCase().replace(/[\s]+/g, '_');
-}
-
+`
var hasProp = Object.prototype.hasOwnProperty,
extendsClass = function(child, parent) {
for (var key in parent) {
@@ -65,43 +22,31 @@ var hasProp = Object.prototype.hasOwnProperty,
class Mongorito
@disconnect: ->
do Client.close
- @connect: (database = '', servers = [], username = '', password = '') ->
- if servers.length is 1
- server = new mongolian servers[0]
- Client = server.db database
- Client.log=
- debug: ->
- info: ->
- warn: ->
- error: ->
- Client.auth username, password if username
- else
- # Support comes soon to Replica Sets
- server = new mongolian servers[0]
- Client = server.db database
- Client.log=
- debug: ->
- info: ->
- warn: ->
- error: ->
- Client.auth username, password if username
+
+ @connect: (servers = []) ->
+ Client = new mongolian servers[0]
+ Client.log=
+ debug: ->
+ info: ->
+ warn: ->
+ error: ->
@cache: (servers = []) ->
Cache = new memcacher servers
@bake: (model) ->
extendsClass(model, MongoritoModel)
object = new model
- model.collection = object.collection
+ model.collectionName = object.collectionName
model.model = model
model
class MongoritoModel
- constructor: (@collection = '') ->
+ constructor: (@collectionName = '') ->
fields: ->
- notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate']
+ notFields = ['constructor', 'save', 'collectionName', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate']
fields = {}
for field of @
fields[field] = @[field] if -1 is notFields.indexOf field
@@ -112,213 +57,66 @@ class MongoritoModel
for item in items
item._id = item._id.toString()
model = new _model
- model.collection = _model.collection
+ model.collectionName = _model.collectionName
for field of item
model[field] = item[field]
models.push model
models
- @findById: (id, callback) ->
- that = @
-
- query = (id, done) ->
- Client.collection(that.collection).find({ _id: new mongolian.ObjectId(id.toString()) }).toArray (err, items) ->
- process.nextTick ->
- for item in items
- item._id = item._id.toString()
- done err, items
-
- if not Cache
- return query id, (err, items) ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models[0]
-
- key = "#{ @collection }-#{ id.toString() }"
-
- Cache.get key, (err, result) ->
- if not result
- query id, (err, items) ->
- Cache.set key, JSON.stringify(items), 2592000, [that.collection], ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
- else
- process.nextTick ->
- models = that.bakeModelsFromItems JSON.parse(result), that.model
- callback err, models
-
- @findWithOrderAndLimit: (criteria, order, limit, skip, callback) ->
- if typeof criteria is 'object'
- if typeof order is 'number'
- if typeof limit is 'function'
- callback = limit
- limit = order
- order = criteria
- criteria = {}
- if typeof limit is 'number'
- if typeof skip is 'function'
- callback = skip
- skip = limit
- limit = order
- order = criteria
- criteria = {}
-
- skip = 0 if not skip
- that = @
-
- query = (criteria, order, limit, skip, done) ->
- Client.collection(that.collection).find(criteria).sort(order).limit(limit).skip(skip).toArray (err, items) ->
- for item in items
- item._id = item._id.toString()
- done err, items
-
- if not Cache
- return query criteria, order, limit, skip, (err, items) ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
-
- key = "#{ @collection }-order-#{ order }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }"
-
- Cache.get key, (err, result) ->
- if not result
- query criteria, order, limit, skip, (err, items) ->
- Cache.set key, JSON.stringify(items), 2592000, [that.collection], ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
- else
- process.nextTick ->
- models = that.bakeModelsFromItems JSON.parse(result), that.model
- callback err, models
-
- @findWithOrder: (criteria, order, callback) ->
- if typeof criteria is 'object' and typeof order is 'function'
- callback = order
- order = criteria
- criteria = {}
- order = { _id: -1 }
-
- that = @
-
- query = (criteria, order, done) ->
- Client.collection(that.collection).find(criteria).sort(order).toArray (err, items) ->
- for item in items
- item._id = item._id.toString()
- done err, items
-
- if not Cache
- return query criteria, order, (err, items) ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
-
- key = "#{ @collection }-order-#{ order }-#{ JSON.stringify(criteria) }"
-
- Cache.get key, (err, result) ->
- if not result
- query criteria, order, (err, items) ->
- Cache.set key, JSON.stringify(items), 2592000, [that.collection], ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
- else
- process.nextTick ->
- models = that.bakeModelsFromItems JSON.parse(result), that.model
- callback err, models
-
- @findWithLimit: (criteria, limit, skip, callback) ->
- if typeof criteria is 'number'
- if typeof limit is 'function'
- callback = limit
- limit = criteria
- criteria = {}
- if typeof limit is 'number'
- if typeof skip is 'function'
- callback = skip
- skip = limit
- criteria = {}
+ @find: (options, callback) ->
+ if typeof options is 'function'
+ callback = options
+ options = {}
else
- if typeof limit is 'function'
- callback = limit
- limit = 10
- if typeof skip is 'function'
- callback = skip
- skip = 0
+ if options.callback
+ callback = options.callback
+ delete options.callback
that = @
- query = (criteria, limit, skip, done) ->
- Client.collection(that.collection).find(criteria).limit(limit).skip(skip).toArray (err, items) ->
+ query = (done) ->
+ fields = {}
+ notFields = ['limit', 'skip', 'sort']
+ for property of options
+ fields[property] = options[property] if options.hasOwnProperty(property) and notFields.indexOf(property) is -1
+ request = Client.collection(that.collectionName).find(fields)
+ request = request.limit options.limit if options.limit
+ request = request.skip options.skip if options.skip
+ request = request.sort options.sort if options.sort
+ request.toArray (err, items) ->
for item in items
item._id = item._id.toString()
done err, items
if not Cache
- return query criteria, limit, skip, (err, items) ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
-
- key = "#{ @collection }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }"
-
- Cache.get key, (err, result) ->
- if not result
- query criteria, limit, skip, (err, items) ->
- Cache.set key, JSON.stringify(items), 2592000, [that.collection], ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
- else
- process.nextTick ->
- models = that.bakeModelsFromItems JSON.parse(result), that.model
- callback err, models
-
- @find: (criteria = {}, callback) ->
- if typeof(criteria) is 'function'
- callback = criteria
- criteria = {}
-
- that = @
-
- query = (criteria, done) ->
- Client.collection(that.collection).find(criteria).toArray (err, items) ->
- for item in items
- item._id = item._id.toString()
- done err, items
-
- if not Cache
- return query criteria, (err, items) ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
+ return query (err, items) ->
+ models = that.bakeModelsFromItems items, that.model
+ callback err, models
- key = "#{ @collection }-#{ JSON.stringify(criteria) }"
+ key = "#{ @collectionName }-#{ JSON.stringify(options) }"
Cache.get key, (err, result) ->
if not result
- query criteria, (err, items) ->
- Cache.set key, JSON.stringify(items), 2592000, [that.collection], ->
- process.nextTick ->
- models = that.bakeModelsFromItems items, that.model
- callback err, models
+ query (err, items) ->
+ Cache.set key, JSON.stringify(items), 2592000, [that.collectionName], ->
+ models = that.bakeModelsFromItems items, that.model
+ callback err, models
else
- process.nextTick ->
- models = that.bakeModelsFromItems JSON.parse(result), that.model
- callback err, models
+ models = that.bakeModelsFromItems JSON.parse(result), that.model
+ callback err, models
save: (callback) ->
that = @
fields = do @fields
- notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'models']
+ notFields = ['constructor', 'save', 'collectionName', 'create', 'fields', 'update', 'remove', 'models']
keys = []
for field of @
keys.push field if -1 is notFields.indexOf field
async.filter keys, (key, nextKey) ->
- if that["validate#{ key.camelize() }"]
- that["validate#{ key.camelize() }"] (valid) ->
+ if that["validate#{ inflect.camelize key }"]
+ that["validate#{ inflect.camelize key }"] (valid) ->
nextKey not valid
else
nextKey false
@@ -331,7 +129,7 @@ class MongoritoModel
else
that.create callback, yes
- if Cache then Cache.delByTag that.collection, performOperation else do performOperation
+ if Cache then Cache.delByTag that.collectionName, performOperation else do performOperation
create: (callback, fromSave = no) ->
object = @fields()
@@ -340,13 +138,12 @@ class MongoritoModel
do @aroundCreate if @['aroundCreate']
that = @
- Client.collection(@collection).insert object, (err, result) ->
+ Client.collection(@collectionName).insert object, (err, result) ->
result._id = result._id.toString()
that._id = result._id
do that.aroundCreate if that['aroundCreate']
do that.afterCreate if that['afterCreate']
- process.nextTick ->
- callback err, result if callback
+ callback err, result if callback
update: (callback, fromSave = no) ->
object = @fields()
@@ -357,11 +154,10 @@ class MongoritoModel
do @aroundUpdate if @['aroundUpdate']
that = @
- Client.collection(@collection).update { _id: _id }, object, (err, rowsUpdated) ->
+ Client.collection(@collectionName).update { _id: _id }, object, (err, rowsUpdated) ->
do that.aroundUpdate if that['aroundUpdate']
do that.afterUpdate if that['afterUpdate']
- process.nextTick ->
- callback err, rowsUpdated if callback
+ callback err, rowsUpdated if callback
remove: (callback) ->
object = @fields()
@@ -371,15 +167,15 @@ class MongoritoModel
do @beforeRemove if @['beforeRemove']
do @aroundRemove if @['aroundRemove']
that = @
- Cache.delByTag @collection, ->
- Client.collection(that.collection).remove { _id: _id }, (err) ->
+ query = ->
+ Client.collection(that.collectionName).remove _id: _id, (err) ->
do that.aroundRemove if that['aroundRemove']
do that.afterRemove if that['afterRemove']
- process.nextTick ->
- callback err if callback
-
-
-class GenericModel extends MongoritoModel
+ callback err if callback
+ if Cache
+ Cache.delByTag @collectionName, query
+ else
+ do query
module.exports=
connect: Mongorito.connect
View
426 lib/mongorito.js
@@ -1,61 +1,17 @@
-var Cache, Client, GenericModel, Mongorito, MongoritoModel, async, memcacher, mongolian,
- __hasProp = Object.prototype.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
+var Cache, Client, Mongorito, MongoritoModel, async, inflect, memcacher, mongolian;
mongolian = require('mongolian');
async = require('async');
memcacher = require('memcacher');
+inflect = require('i');
+
Client = void 0;
Cache = void 0;
-String.prototype.plural = function() {
- var s = this.trim().toLowerCase();
- end = s.substr(-1);
- if(end == 'y') {
- var vowels = ['a', 'e', 'i', 'o', 'u'];
- s = s.substr(-2, 1) in vowels ? s + 's' : s.substr(0, s.length-1) + 'ies';
- } else if(end == 'h') {
- s += s.substr(-2) == 'ch' || s.substr(-2) == 'sh' ? 'es' : 's';
- } else if(end == 's') {
- s += 'es';
- } else {
- s += 's';
- }
- return s;
-}
-
-String.prototype.singular = function() {
- var s = this.trim().toLowerCase();
- var end = s.substr(-3);
- if(end == 'ies') {
- s = s.substr(0, s.length-3) + 'y';
- } else if(end == 'ses') {
- s = s.substr(0, s.length-2);
- } else {
- end = s.substr(-1);
- if(end == 's') {
- s = s.substr(0, s.length-1);
- }
- }
- return s;
-}
-
-String.prototype.camelize = function() {
- var s = 'x_' + this.trim().toLowerCase();
- s = s.replace(/[\s_]/g, ' ');
- s = s.replace(/^(.)|\s(.)/g, function($1) {
- return $1.toUpperCase();
- });
- return s.replace(/ /g, '').substr(1);
-}
-
-String.prototype.underscore = function() {
- return this.trim().toLowerCase().replace(/[\s]+/g, '_');
-}
var hasProp = Object.prototype.hasOwnProperty,
extendsClass = function(child, parent) {
@@ -78,33 +34,15 @@ Mongorito = (function() {
return Client.close();
};
- Mongorito.connect = function(database, servers, username, password) {
- var server;
- if (database == null) database = '';
+ Mongorito.connect = function(servers) {
if (servers == null) servers = [];
- if (username == null) username = '';
- if (password == null) password = '';
- if (servers.length === 1) {
- server = new mongolian(servers[0]);
- Client = server.db(database);
- Client.log = {
- debug: function() {},
- info: function() {},
- warn: function() {},
- error: function() {}
- };
- if (username) return Client.auth(username, password);
- } else {
- server = new mongolian(servers[0]);
- Client = server.db(database);
- Client.log = {
- debug: function() {},
- info: function() {},
- warn: function() {},
- error: function() {}
- };
- if (username) return Client.auth(username, password);
- }
+ Client = new mongolian(servers[0]);
+ return Client.log = {
+ debug: function() {},
+ info: function() {},
+ warn: function() {},
+ error: function() {}
+ };
};
Mongorito.cache = function(servers) {
@@ -116,7 +54,7 @@ Mongorito = (function() {
var object;
extendsClass(model, MongoritoModel);
object = new model;
- model.collection = object.collection;
+ model.collectionName = object.collectionName;
model.model = model;
return model;
};
@@ -127,13 +65,13 @@ Mongorito = (function() {
MongoritoModel = (function() {
- function MongoritoModel(collection) {
- this.collection = collection != null ? collection : '';
+ function MongoritoModel(collectionName) {
+ this.collectionName = collectionName != null ? collectionName : '';
}
MongoritoModel.prototype.fields = function() {
var field, fields, notFields;
- notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate'];
+ notFields = ['constructor', 'save', 'collectionName', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate'];
fields = {};
for (field in this) {
if (-1 === notFields.indexOf(field)) fields[field] = this[field];
@@ -148,7 +86,7 @@ MongoritoModel = (function() {
item = items[_i];
item._id = item._id.toString();
model = new _model;
- model.collection = _model.collection;
+ model.collectionName = _model.collectionName;
for (field in item) {
model[field] = item[field];
}
@@ -157,245 +95,32 @@ MongoritoModel = (function() {
return models;
};
- MongoritoModel.findById = function(id, callback) {
- var key, query, that;
- that = this;
- query = function(id, done) {
- return Client.collection(that.collection).find({
- _id: new mongolian.ObjectId(id.toString())
- }).toArray(function(err, items) {
- return process.nextTick(function() {
- var item, _i, _len;
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- item._id = item._id.toString();
- }
- return done(err, items);
- });
- });
- };
- if (!Cache) {
- return query(id, function(err, items) {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models[0]);
- });
- }
- key = "" + this.collection + "-" + (id.toString());
- return Cache.get(key, function(err, result) {
- if (!result) {
- return query(id, function(err, items) {
- return Cache.set(key, JSON.stringify(items), 2592000, [that.collection], function() {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- });
- } else {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(JSON.parse(result), that.model);
- return callback(err, models);
- });
- }
- });
- };
-
- MongoritoModel.findWithOrderAndLimit = function(criteria, order, limit, skip, callback) {
- var key, query, that;
- if (typeof criteria === 'object') {
- if (typeof order === 'number') {
- if (typeof limit === 'function') {
- callback = limit;
- limit = order;
- order = criteria;
- criteria = {};
- }
- if (typeof limit === 'number') {
- if (typeof skip === 'function') {
- callback = skip;
- skip = limit;
- limit = order;
- order = criteria;
- criteria = {};
- }
- }
- }
- }
- if (!skip) skip = 0;
- that = this;
- query = function(criteria, order, limit, skip, done) {
- return Client.collection(that.collection).find(criteria).sort(order).limit(limit).skip(skip).toArray(function(err, items) {
- var item, _i, _len;
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- item._id = item._id.toString();
- }
- return done(err, items);
- });
- };
- if (!Cache) {
- return query(criteria, order, limit, skip, function(err, items) {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- }
- key = "" + this.collection + "-order-" + order + "-limit-" + limit + "-skip-" + skip + "-" + (JSON.stringify(criteria));
- return Cache.get(key, function(err, result) {
- if (!result) {
- return query(criteria, order, limit, skip, function(err, items) {
- return Cache.set(key, JSON.stringify(items), 2592000, [that.collection], function() {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- });
- } else {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(JSON.parse(result), that.model);
- return callback(err, models);
- });
- }
- });
- };
-
- MongoritoModel.findWithOrder = function(criteria, order, callback) {
+ MongoritoModel.find = function(options, callback) {
var key, query, that;
- if (typeof criteria === 'object' && typeof order === 'function') {
- callback = order;
- order = criteria;
- criteria = {};
- order = {
- _id: -1
- };
- }
- that = this;
- query = function(criteria, order, done) {
- return Client.collection(that.collection).find(criteria).sort(order).toArray(function(err, items) {
- var item, _i, _len;
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- item._id = item._id.toString();
- }
- return done(err, items);
- });
- };
- if (!Cache) {
- return query(criteria, order, function(err, items) {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- }
- key = "" + this.collection + "-order-" + order + "-" + (JSON.stringify(criteria));
- return Cache.get(key, function(err, result) {
- if (!result) {
- return query(criteria, order, function(err, items) {
- return Cache.set(key, JSON.stringify(items), 2592000, [that.collection], function() {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- });
- } else {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(JSON.parse(result), that.model);
- return callback(err, models);
- });
- }
- });
- };
-
- MongoritoModel.findWithLimit = function(criteria, limit, skip, callback) {
- var key, query, that;
- if (typeof criteria === 'number') {
- if (typeof limit === 'function') {
- callback = limit;
- limit = criteria;
- criteria = {};
- }
- if (typeof limit === 'number') {
- if (typeof skip === 'function') {
- callback = skip;
- skip = limit;
- criteria = {};
- }
- }
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
} else {
- if (typeof limit === 'function') {
- callback = limit;
- limit = 10;
- }
- if (typeof skip === 'function') {
- callback = skip;
- skip = 0;
+ if (options.callback) {
+ callback = options.callback;
+ delete options.callback;
}
}
that = this;
- query = function(criteria, limit, skip, done) {
- return Client.collection(that.collection).find(criteria).limit(limit).skip(skip).toArray(function(err, items) {
- var item, _i, _len;
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- item._id = item._id.toString();
+ query = function(done) {
+ var fields, notFields, property, request;
+ fields = {};
+ notFields = ['limit', 'skip', 'sort'];
+ for (property in options) {
+ if (options.hasOwnProperty(property) && notFields.indexOf(property) === -1) {
+ fields[property] = options[property];
}
- return done(err, items);
- });
- };
- if (!Cache) {
- return query(criteria, limit, skip, function(err, items) {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- }
- key = "" + this.collection + "-limit-" + limit + "-skip-" + skip + "-" + (JSON.stringify(criteria));
- return Cache.get(key, function(err, result) {
- if (!result) {
- return query(criteria, limit, skip, function(err, items) {
- return Cache.set(key, JSON.stringify(items), 2592000, [that.collection], function() {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
- });
- });
- } else {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(JSON.parse(result), that.model);
- return callback(err, models);
- });
}
- });
- };
-
- MongoritoModel.find = function(criteria, callback) {
- var key, query, that;
- if (criteria == null) criteria = {};
- if (typeof criteria === 'function') {
- callback = criteria;
- criteria = {};
- }
- that = this;
- query = function(criteria, done) {
- return Client.collection(that.collection).find(criteria).toArray(function(err, items) {
+ request = Client.collection(that.collectionName).find(fields);
+ if (options.limit) request = request.limit(options.limit);
+ if (options.skip) request = request.skip(options.skip);
+ if (options.sort) request = request.sort(options.sort);
+ return request.toArray(function(err, items) {
var item, _i, _len;
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
@@ -405,32 +130,26 @@ MongoritoModel = (function() {
});
};
if (!Cache) {
- return query(criteria, function(err, items) {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
+ return query(function(err, items) {
+ var models;
+ models = that.bakeModelsFromItems(items, that.model);
+ return callback(err, models);
});
}
- key = "" + this.collection + "-" + (JSON.stringify(criteria));
+ key = "" + this.collectionName + "-" + (JSON.stringify(options));
return Cache.get(key, function(err, result) {
+ var models;
if (!result) {
- return query(criteria, function(err, items) {
- return Cache.set(key, JSON.stringify(items), 2592000, [that.collection], function() {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(items, that.model);
- return callback(err, models);
- });
+ return query(function(err, items) {
+ return Cache.set(key, JSON.stringify(items), 2592000, [that.collectionName], function() {
+ var models;
+ models = that.bakeModelsFromItems(items, that.model);
+ return callback(err, models);
});
});
} else {
- return process.nextTick(function() {
- var models;
- models = that.bakeModelsFromItems(JSON.parse(result), that.model);
- return callback(err, models);
- });
+ models = that.bakeModelsFromItems(JSON.parse(result), that.model);
+ return callback(err, models);
}
});
};
@@ -439,14 +158,14 @@ MongoritoModel = (function() {
var field, fields, keys, notFields, that;
that = this;
fields = this.fields();
- notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'models'];
+ notFields = ['constructor', 'save', 'collectionName', 'create', 'fields', 'update', 'remove', 'models'];
keys = [];
for (field in this) {
if (-1 === notFields.indexOf(field)) keys.push(field);
}
return async.filter(keys, function(key, nextKey) {
- if (that["validate" + (key.camelize())]) {
- return that["validate" + (key.camelize())](function(valid) {
+ if (that["validate" + (inflect.camelize(key))]) {
+ return that["validate" + (inflect.camelize(key))](function(valid) {
return nextKey(!valid);
});
} else {
@@ -463,7 +182,7 @@ MongoritoModel = (function() {
}
};
if (Cache) {
- return Cache.delByTag(that.collection, performOperation);
+ return Cache.delByTag(that.collectionName, performOperation);
} else {
return performOperation();
}
@@ -477,14 +196,12 @@ MongoritoModel = (function() {
if (this['beforeCreate']) this.beforeCreate();
if (this['aroundCreate']) this.aroundCreate();
that = this;
- return Client.collection(this.collection).insert(object, function(err, result) {
+ return Client.collection(this.collectionName).insert(object, function(err, result) {
result._id = result._id.toString();
that._id = result._id;
if (that['aroundCreate']) that.aroundCreate();
if (that['afterCreate']) that.afterCreate();
- return process.nextTick(function() {
- if (callback) return callback(err, result);
- });
+ if (callback) return callback(err, result);
});
};
@@ -497,53 +214,42 @@ MongoritoModel = (function() {
if (this['beforeUpdate']) this.beforeUpdate();
if (this['aroundUpdate']) this.aroundUpdate();
that = this;
- return Client.collection(this.collection).update({
+ return Client.collection(this.collectionName).update({
_id: _id
}, object, function(err, rowsUpdated) {
if (that['aroundUpdate']) that.aroundUpdate();
if (that['afterUpdate']) that.afterUpdate();
- return process.nextTick(function() {
- if (callback) return callback(err, rowsUpdated);
- });
+ if (callback) return callback(err, rowsUpdated);
});
};
MongoritoModel.prototype.remove = function(callback) {
- var object, that, _id;
+ var object, query, that, _id;
object = this.fields();
_id = new mongolian.ObjectId(object._id);
if (this['beforeRemove']) this.beforeRemove();
if (this['aroundRemove']) this.aroundRemove();
that = this;
- return Cache.delByTag(this.collection, function() {
- return Client.collection(that.collection).remove({
+ query = function() {
+ return Client.collection(that.collectionName).remove({
_id: _id
}, function(err) {
if (that['aroundRemove']) that.aroundRemove();
if (that['afterRemove']) that.afterRemove();
- return process.nextTick(function() {
- if (callback) return callback(err);
- });
+ if (callback) return callback(err);
});
- });
+ };
+ if (Cache) {
+ return Cache.delByTag(this.collectionName, query);
+ } else {
+ return query();
+ }
};
return MongoritoModel;
})();
-GenericModel = (function(_super) {
-
- __extends(GenericModel, _super);
-
- function GenericModel() {
- GenericModel.__super__.constructor.apply(this, arguments);
- }
-
- return GenericModel;
-
-})(MongoritoModel);
-
module.exports = {
connect: Mongorito.connect,
disconnect: Mongorito.disconnect,
View
5 package.json
@@ -1,13 +1,14 @@
{
"name": "mongorito",
- "version": "0.2.2",
+ "version": "0.3.0",
"description": "ODM for MongoDB.",
"keywords": ["mongo", "mongodb"],
"author": "Vadim Demedes <sbioko@gmail.com>",
"dependencies": {
"async": "*",
"mongolian": "*",
- "memcacher": "*"
+ "memcacher": "*",
+ "i": "*"
},
"devDependencies": {
"should": "*"
View
75 test/mongorito.test.coffee
@@ -0,0 +1,75 @@
+Mongorito = require '../lib/mongorito'
+
+Mongorito.connect ['mongo://127.0.0.1:27017/mongorito']
+Mongorito.cache ['127.0.0.1:11211']
+
+require 'should'
+async = require 'async'
+
+class Post
+ constructor: ->
+ super 'posts'
+
+Post = Mongorito.bake Post
+
+describe 'Mongorito', ->
+ describe 'creating new record', ->
+ it 'should create new record in "posts" collection', (done) ->
+ post = new Post
+ post.title = 'Very nice post!'
+ post.author = 'Vadim'
+ post.save ->
+ Post.find (err, posts) ->
+ posts.length.should.equal 1
+ do done
+
+ describe 'editing record', ->
+ it 'should save edited version of the post', (done) ->
+ Post.find (err, posts) ->
+ post = posts[0]
+ post.title = 'Edited title!'
+ post.save ->
+ do done
+
+ describe 'getting record', ->
+ it 'should fetch just edited post', (done) ->
+ Post.find (err, posts) ->
+ posts[0].title.should.equal 'Edited title!'
+ do done
+
+ describe 'fetching records', ->
+ it 'should fetch only one post', (done) ->
+ Post.find limit: 1, (err, posts) ->
+ posts.length.should.equal 1
+ do done
+
+ it 'should fetch post by title', (done) ->
+ Post.find title: 'Edited title!', (err, posts) ->
+ posts.length.should.equal 1
+ do done
+
+ it 'should create another post and fetch only one', (done) ->
+ post = new Post
+ post.title = 'Just created'
+ post.author = 'Vadim'
+ post.save ->
+ Post.find limit: 1, skip: 1, (err, posts) ->
+ posts.length.should.equal 1
+ do done
+
+ it 'should fetch posts, ordering by the time of creation', (done) ->
+ Post.find sort: { _id: -1 }, (err, posts) ->
+ posts[0].title is 'Just created' and posts.length.should.equal 2
+ do done
+
+
+ describe 'deleting records', ->
+ it 'should remove all posts', (done) ->
+ Post.find (err, posts) ->
+ async.forEach posts, (post, nextPost) ->
+ post.remove ->
+ do nextPost
+ , ->
+ Post.find (err, posts) ->
+ posts.length.should.equal 0
+ do done

0 comments on commit 417d05a

Please sign in to comment.