Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created February 2, 2012 03:04
Show Gist options
  • Save aheckmann/1721157 to your computer and use it in GitHub Desktop.
Save aheckmann/1721157 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, tojson = mongoose.Document.prototype.toJSON;
mongoose.connect('localhost', 'testing_tojsonWithVirtuals');
var PersonSchema = new Schema({
name : String
, age : Number
});
PersonSchema.methods.toJSON = function (options) {
var res = tojson.call(this, options);
res.was_in_to_json = true;
return res;
}
var StorySchema = new Schema({
creators : [PersonSchema]
, title : String
});
StorySchema.methods.toJSON = PersonSchema.methods.toJSON;
var Story = mongoose.model('Story', StorySchema);
mongoose.connection.on('open', function () {
person1 = { name: 'Person1', age: 42 };
person2 = { name: 'Person2', age: 42 };
Story.create({ title: 'Test', creators: [person1, person2] }, function (err, story) {
if (err) return console.error(err.stack||err);
Story.findById(story).run(function (err, doc) {
if (err) return console.error(err.stack||err);
console.error(doc.toJSON());
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