@@ -98,26 +98,38 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) {
9898 */
9999
100100DocumentArray . prototype . cast = function ( value , doc , init ) {
101+ var retval = value ;
101102 if ( Array . isArray ( value ) ) {
102- if ( ! ( value instanceof MongooseDocumentArray ) )
103- value = new MongooseDocumentArray ( value , this . path , doc ) ;
104-
105- for ( var i = 0 , l = value . length ; i < l ; i ++ ) {
106- if ( ! ( value [ i ] instanceof Subdocument ) ) {
107- var doc = new this . caster ( null , value ) ;
108-
109- if ( init ) {
110- // skip _id for pre-init hooks
111- delete doc . _doc . _id ;
103+ if ( ! ( value instanceof MongooseDocumentArray ) ) {
104+ if ( doc )
105+ retval = doc . get ( this . path ) ;
106+ if ( ! retval )
107+ retval = new MongooseDocumentArray ( [ ] , this . path , doc ) ;
108+
109+ for ( var i = 0 , l = value . length ; i < l ; i ++ ) {
110+ var subdoc = null ;
111+ if ( ! ( value [ i ] instanceof Subdocument ) ) {
112+ for ( var j = 0 , k = retval . length ; value [ i ] [ '_id' ] && j < k ; j ++ ) {
113+ if ( retval [ j ] . _id . toString ( ) ===
114+ value [ i ] [ '_id' ] . toString ( ) ) {
115+ subdoc = retval [ j ] ;
116+ break ;
117+ }
118+ }
119+ if ( ! subdoc ) {
120+ subdoc = new this . caster ( null , retval ) ;
121+ Array . prototype . push . apply ( retval , [ subdoc ] ) ;
122+ }
123+ if ( init ) {
124+ delete subdoc . _doc . _id ;
125+ subdoc . init ( value [ i ] ) ;
126+ } else {
127+ subdoc . set ( value [ i ] ) ;
128+ }
112129 }
113-
114- value [ i ] = init
115- ? doc . init ( value [ i ] )
116- : doc . set ( value [ i ] ) ;
117130 }
118131 }
119-
120- return value ;
132+ return retval ;
121133 } else {
122134 return this . cast ( [ value ] , doc ) ;
123135 }
0 commit comments