public
Created

Mongoose toJSON

  • Download Gist
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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();
});
});
});
});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.