Skip to content

Commit

Permalink
fixed #1376; subdocuments now use own toJSON opts
Browse files Browse the repository at this point in the history
subdocuments and populated paths were using the parent's toJSON options
instead of their own. This fixes that.
  • Loading branch information
ebensing authored and aheckmann committed Aug 21, 2013
1 parent 0764330 commit 7a5f700
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -1543,12 +1543,18 @@ Document.prototype.toJSON = function (options) {
// check for object type since an array of documents
// being stringified passes array indexes instead
// of options objects. JSON.stringify([doc, doc])
if (!(options && 'Object' == options.constructor.name)) {
// 8/5/2013-(3.7)
// The second check here is to make sure that populated documents (or
// subdocuments) use their own options for `.toJSON()` instead of their
// parent's
if (!(options && 'Object' == options.constructor.name)
|| ((!options || options.json) && this.schema.options.toJSON)) {
options = this.schema.options.toJSON
? clone(this.schema.options.toJSON)
: {};
}
options.json = true;

return this.toObject(options);
};

Expand Down
31 changes: 31 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,37 @@ describe('document', function(){
assert.equal(obj._id, oidString);
done();
});
it('jsonifying an object\'s populated items works (gh-1376)', function(done){
var db = start();
var userSchema, User, groupSchema, Group;

userSchema = Schema({name: String});
// includes virtual path when 'toJSON'
userSchema.set('toJSON', {getters: true});
userSchema.virtual('hello').get(function() {
return 'Hello, ' + this.name;
});
User = db.model('User', userSchema);

groupSchema = Schema({
name: String,
_users: [{type: Schema.ObjectId, ref: 'User'}]
});

Group = db.model('Group', groupSchema);

User.create({name: 'Alice'}, {name: 'Bob'}, function(err, alice, bob) {
assert.ifError(err);

new Group({name: 'mongoose', _users: [alice, bob]}).save(function(err, group) {
Group.findById(group).populate('_users').exec(function(err, group) {
assert.ifError(err);
assert.ok(group.toJSON()._users[0].hello);
done();
});
});
});
})

describe('#update', function(){
it('returns a Query', function(done){
Expand Down

0 comments on commit 7a5f700

Please sign in to comment.