Skip to content

Instantly share code, notes, and snippets.

@liamcurry
Created June 10, 2011 21:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liamcurry/1019779 to your computer and use it in GitHub Desktop.
Save liamcurry/1019779 to your computer and use it in GitHub Desktop.
Add embedded document helpers to Mongoose.js
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