Created
January 9, 2012 17:57
-
-
Save aheckmann/1584121 to your computer and use it in GitHub Desktop.
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'); | |
mongoose.connect('localhost', 'testing_tojsonWithVirtuals'); | |
var schema = new mongoose.Schema({ | |
name: { | |
first: String | |
, last: String | |
} | |
, age: Number | |
}); | |
schema.virtual('fullname').get(function () { | |
return this.name.first + ' ' + this.name.last; | |
}); | |
schema.virtual('name.silly').get(function () { | |
return this.fullname + ' is silly'; | |
}); | |
schema.virtual('nested.thing').get(function () { | |
return this.age + ' | ' + this.fullname; | |
}); | |
// toJSON with virtuals | |
schema.methods.toJSON2 = function () { | |
var json = this.toJSON(); | |
var schema = this.schema | |
, virtuals = schema.virtuals | |
, paths = Object.keys(virtuals) | |
, i = paths.length | |
, path | |
while (i--) { | |
path = paths[i]; | |
var parts = path.split('.') | |
, plen = parts.length | |
, last = plen - 1 | |
, branch = json | |
, part | |
for (var pp = 0; pp < plen; ++pp) { | |
part = parts[pp]; | |
if (pp === last) { | |
branch[part] = this.get(path); | |
} else { | |
branch = branch[part] || (branch[part] = {}); | |
} | |
} | |
} | |
return json; | |
} | |
var A = mongoose.model('A', schema); | |
mongoose.connection.on('open', function () { | |
A.create({ name: { first: 'tetris', last: 'party' }, age: 1 }, function (err, a) { | |
if (err) return console.error(err.stack||err); | |
A.findById(a, function (err, doc) { | |
if (err) return console.error(err.stack||err); | |
console.error(doc); | |
console.error(doc.toJSON2()); | |
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