LearnBoost/mongoose — pull request #564 by gitfy (2011-10-13 20:38:21+00:00)
Title: fix for hooks call - multi-level embedded documents

Hi,
At the moment, the pre-save hooks doesn't get called for embedded document below the second level. This change will fix this.

Just to make it clear, i have shown the test below :

var grandSchema = new Schema({ name : String });
grandSchema.pre('save', function (next) {
this.name = 'grand';
next();
});
var childSchema = new Schema({ name : String, grand : [grandSchema]});
childSchema.pre('save', function (next) {
this.name = 'child';
next();
});
var schema = new Schema({ name: String, child : [childSchema] });

schema.pre('save', function (next) {
this.name = 'parent';
next();
});

var S = db.model('presave_hook', schema, 'presave_hook');
var s = new S({ name : 'a' , child : [ { name : 'b', grand : [{ name : 'c'}] } ]});

s.save(function (err, doc) {
db.close();
should.strictEqual(null, err);
doc.name.should.eql('parent');
doc.name.child[0].name.should.eql('child');
doc.name.child[0].grand[0].name.should.eql('grand');

});

Here the pre-save for the grand schema will also be called, which wasn't happening before.

Let me know if my fix has any issues. The request have test case as well.

Thanks.