Created
January 10, 2012 14:09
-
-
Save jerem/1589265 to your computer and use it in GitHub Desktop.
Mongoose toJSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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