Skip to content

Instantly share code, notes, and snippets.

Created February 18, 2014 20:43
Show Gist options
  • Save anonymous/9079677 to your computer and use it in GitHub Desktop.
Save anonymous/9079677 to your computer and use it in GitHub Desktop.
Non-destructive mongoose.Document.prototype.toObject
var mongoose = require('mongoose');
var native = mongoose.Document.prototype.toObject;
module.exports = function(schema/* options [could make it safer :)]*/) {
schema.methods.toObject = function() {
var _this = this;
var obj = mongoose.Document.prototype.toObject.apply(this, arguments);
var extraneous = Object.keys(this).filter(function(key) {
return IGNORED_KEYS.indexOf(key) !== -1;
});
return _.reduce(extraneous, function(key) {
obj[key] = _this[key];
return obj;
}, obj);
}
};
var IGNORED_KEYS = Object.keys(mongoose.Document.prototype).concat([
'$__', 'isNew', 'errors', '_maxListeners', '_doc', '_pres', '_posts', 'save', '_events'
// there's probably a way to infer this
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment