diff --git a/lib/types/documentarray.js b/lib/types/documentarray.js index 94d77e6f4c3..a4c2f94b83c 100644 --- a/lib/types/documentarray.js +++ b/lib/types/documentarray.js @@ -58,6 +58,11 @@ MongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype; MongooseDocumentArray.prototype._cast = function (value) { if (value instanceof this._schema.casterConstructor) { + if (!(value.__parent && value.__parentArray)) { + // value may have been created using array.create() + value.__parent = this._parent; + value.__parentArray = this; + } return value; } diff --git a/test/types.documentarray.test.js b/test/types.documentarray.test.js index f4ab6684f55..3092d4a7bc8 100644 --- a/test/types.documentarray.test.js +++ b/test/types.documentarray.test.js @@ -240,6 +240,16 @@ describe('types.documentarray', function(){ }) }) }) + it('corrects #ownerDocument() if value was created with array.create() (gh-1385)', function(done){ + var mg = new mongoose.Mongoose; + var M = mg.model('1385', { docs: [{ name: String }] }); + var m = new M; + var doc = m.docs.create({ name: 'test 1385' }); + assert.notEqual(String(doc.ownerDocument()._id), String(m._id)); + m.docs.push(doc); + assert.equal(doc.ownerDocument()._id, String(m._id)); + done(); + }) }) it('#push should work on EmbeddedDocuments more than 2 levels deep', function (done) {