Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.