Permalink
Browse files

fixed; do not recast embedded docs unnecessarily

  • Loading branch information...
1 parent 0606544 commit 3365bfa6f9ae29630a07837bd3538829d8051642 @aheckmann aheckmann committed Oct 2, 2012
Showing with 50 additions and 2 deletions.
  1. +4 −2 lib/types/documentarray.js
  2. +46 −0 test/types.documentarray.test.js
@@ -56,8 +56,10 @@ MongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype;
*/
MongooseDocumentArray.prototype._cast = function (value) {
- var doc = new this._schema.casterConstructor(value, this);
- return doc;
+ if (value instanceof this._schema.casterConstructor)
+ return value;
+
+ return new this._schema.casterConstructor(value, this);
};
/**
@@ -191,6 +191,52 @@ describe('types.documentarray', function(){
assert.ok(subdoc instanceof EmbeddedDocument);
})
})
+
+ describe('push()', function(){
+ it('does not re-cast instances of its embedded doc xxxxxx', function(done){
+ var db = start();
+
+ var child = new Schema({ name: String, date: Date });
+ child.pre('save', function (next) {
+ this.date = new Date;
+ next();
+ });
+ var schema = Schema({ children: [child] });
+ var M = db.model('embeddedDocArray-push-re-cast', schema, 'edarecast-'+random());
+ var m = new M;
+ m.save(function (err) {
+ assert.ifError(err);
+ M.findById(m._id, function (err, doc) {
+ assert.ifError(err);
+ var c = doc.children.create({ name: 'first' })
+ assert.equal(undefined, c.date);
+ doc.children.push(c);
+ assert.equal(undefined, c.date);
+ doc.save(function (err) {
+ assert.ifError(err);
+ assert.ok(doc.children[doc.children.length-1].date);
+ assert.equal(c.date, doc.children[doc.children.length-1].date);
+
+ doc.children.push(c);
+ doc.children.push(c);
+
+ doc.save(function (err) {
+ assert.ifError(err);
+ M.findById(m._id, function (err, doc) {
+ db.close()
+ assert.ifError(err);
+ assert.equal(3, doc.children.length);
+ doc.children.forEach(function (child) {
+ assert.equal(doc.children[0].id, child.id);
+ })
+ done();
+ })
+ })
+ })
+ })
+ })
+ })
+ })
})
it('#push should work on EmbeddedDocuments more than 2 levels deep', function (done) {

0 comments on commit 3365bfa

Please sign in to comment.