Created
June 10, 2011 21:06
-
-
Save liamcurry/1019779 to your computer and use it in GitHub Desktop.
Add embedded document helpers to Mongoose.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mongoose.Types.DocumentArray.prototype.sortByDir = function(direction, path) { | |
this.sort(function(a, b) { | |
var aVal = a.get(path), | |
bVal = b.get(path); | |
if (!aVal && !bVal) return 0; | |
if (!aVal) return 1; | |
if (!bVal) return -1; | |
if (direction > 0) return !(aVal < bVal); | |
return (aVal < bVal); | |
}); | |
}; | |
mongoose.Types.DocumentArray.prototype.sortAsc = function(path) { | |
this.sortByDir(1, path); | |
}; | |
mongoose.Types.DocumentArray.prototype.sortDesc = function(path) { | |
this.sortByDir(-1, path); | |
}; | |
mongoose.Types.DocumentArray.prototype.find = function(query, limit) { | |
var results = []; | |
if (!limit) limit = this.length; | |
this.forEach(function(doc) { | |
var isMatch = true; | |
for (var key in query) { | |
if (doc.get(key) != query[key]) { | |
isMatch = false; | |
} | |
} | |
if (isMatch) { | |
results.push(doc); | |
if (results.length === limit) { | |
return results; | |
} | |
} | |
}); | |
return results; | |
}; | |
mongoose.Types.DocumentArray.prototype.findOne = function(query) { | |
return this.find(query, 1)[0]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment