Skip to content

Instantly share code, notes, and snippets.

@yamadapc
Forked from anonymous/unsafe-toobject.js
Created February 18, 2014 20:45
Show Gist options
  • Save yamadapc/9079722 to your computer and use it in GitHub Desktop.
Save yamadapc/9079722 to your computer and use it in GitHub Desktop.
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
]);
@yamadapc
Copy link
Author

I created this anonymously by mistake... ooops
This means:

var SomethingSchema = new mongoose.Schema({
  blabla: String
});

var Something = mongoose.model('Something', SomethingSchema);

var doc = new Something({
  blabla: 'adsf'
});

doc.bibibi = 'something actually important';

doc.toObject() // =>
// { blabla: 'adsf' }

But if this module is plugged-in

doc.toObject() // =>
// { blabla: 'asdf', bibibi: 'something actually important' }

@yamadapc
Copy link
Author

The IGNORED_KEYS variable should always also consider the Schema.reserved keys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment