Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created October 26, 2012 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aheckmann/3959722 to your computer and use it in GitHub Desktop.
Save aheckmann/3959722 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
var dbname = 'testing_tojson';
console.log('dbname: %s', dbname);
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function () {
console.error('connection error', arguments);
});
var schema = new Schema({
name: String
});
//schema.set('toJSON', { hide: '_id' })
// overriding toJSON
var toJSON = mongoose.Document.prototype.toJSON;
schema.methods.toJSON = function (opts) {
var ret = toJSON.apply(this, arguments);
var hide = opts && opts.hide
|| this.schema.options.toJSON && this.schema.options.toJSON.hide;
if (hide) {
hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
var a = new A({ name: 'tojson' });
/**
* Test our plugin
*/
//console.log('hidden', a.toJSON())
console.log('hidden', a.toJSON({ hide: '_id' }))
a.save(function (err, a) {
if (err) return done(err);
A.findById(a, function (err, doc) {
console.error('found', doc);
done(err);
});
})
});
function done (err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment