Skip to content

Instantly share code, notes, and snippets.

@jerem
Created January 10, 2012 14:09
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 jerem/1589265 to your computer and use it in GitHub Desktop.
Save jerem/1589265 to your computer and use it in GitHub Desktop.
Mongoose toJSON
var mongoose = require('mongoose')
, Schema = mongoose.Schema
mongoose.connect('localhost', 'testing_tojsonWithVirtuals');
var PersonSchema = new Schema({
name : String
, age : Number
});
var StorySchema = new Schema({
_creator : { type: Schema.ObjectId, ref: 'Person' }
, title : String
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Story.prototype._toJSON = Story.prototype.toJSON;
Story.prototype.toJSON = function() {
var res = this._toJSON();
res.was_in_to_json = true;
return res;
}
Person.prototype._toJSON = Person.prototype.toJSON;
Person.prototype.toJSON = function() {
var res = this._toJSON();
res.was_in_to_json = true;
return res;
}
mongoose.connection.on('open', function () {
Person.create({ name: 'Jerem', age: 42 }, function (err, person) {
if (err) return console.error(err.stack||err);
Story.create({ title: 'Test', _creator: person }, function (err, story) {
if (err) return console.error(err.stack||err);
Story.findById(story).populate('_creator').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