Skip to content

Commit

Permalink
fixed Automattic#1412; Subdocuments use their own transform
Browse files Browse the repository at this point in the history
Made it such that subdocuments will use their own transform function
instead of their parent's when `toObject()` is called
  • Loading branch information
ebensing committed Aug 21, 2013
1 parent ae75d12 commit ea773ab
Show file tree
Hide file tree
Showing 2 changed files with 46 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 @@ -1464,7 +1464,13 @@ Document.prototype.toObject = function (options) {
applyGetters(this, ret, 'paths', options);
}

if (true === options.transform) {
// In the case where a subdocument has its own transform function, we need to
// check and see if the parent has a transform (options.transform) and if the
// child schema has a transform (this.schema.options.toObject) In this case,
// we need to adjust options.transform to be the child schema's transform and
// not the parent schema's
if (true === options.transform ||
(this.schema.options.toObject && options.transform)) {
var opts = options.json
? this.schema.options.toJSON
: this.schema.options.toObject;
Expand Down
39 changes: 39 additions & 0 deletions test/types.documentarray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,45 @@ describe('types.documentarray', function(){
assert.equal(undefined, delta.$pushAll.docs[0].changed);
done();
})
it('uses the correct transform (gh-1412)', function(done){
var db = start();
var FirstSchema = new Schema({
second: [SecondSchema],
});

FirstSchema.set('toObject', {
transform: function first(doc, ret, options) {
ret.firstToObject = true;
return ret;
},
});

var SecondSchema = new Schema({});

SecondSchema.set('toObject', {
transform: function second(doc, ret, options) {
ret.secondToObject = true;
return ret;
},
});

var First = db.model('first', FirstSchema);
var Second = db.model('second', SecondSchema);

var first = new First({
});

first.second.push(new Second());
first.second.push(new Second());
var obj = first.toObject();

assert.ok(obj.firstToObject);
assert.ok(obj.second[0].secondToObject);
assert.ok(obj.second[1].secondToObject);
assert.ok(!obj.second[0].firstToObject);
assert.ok(!obj.second[1].firstToObject);
done();
})
})

describe('create()', function(){
Expand Down

0 comments on commit ea773ab

Please sign in to comment.