1
+ import dot from 'dot-object' ;
1
2
import CollectionNode from '../nodes/collectionNode.js' ;
2
3
import FieldNode from '../nodes/fieldNode.js' ;
3
4
import ReducerNode from '../nodes/reducerNode.js' ;
@@ -90,6 +91,32 @@ function isProjectionOperatorExpression(body) {
90
91
return false ;
91
92
}
92
93
94
+ function tryFindLink ( root , dottizedPath ) {
95
+ // This would be the link in form of {nestedDocument: {linkedCollection: {...fields...}}}
96
+ const parts = dottizedPath . split ( '.' ) ;
97
+ const firstPart = parts . slice ( 0 , 2 ) ;
98
+ // Here we have a situation where we have link inside a nested document of a nested document
99
+ // {nestedDocument: {subnestedDocument: {linkedCollection: {...fields...}}}
100
+ const nestedParts = parts . slice ( 2 ) ;
101
+
102
+ const potentialLinks = nestedParts . reduce ( ( acc , part ) => {
103
+ return [
104
+ ...acc ,
105
+ `${ _ . last ( acc ) } .${ part } ` ,
106
+ ] ;
107
+ } , [ firstPart . join ( '.' ) ] ) ;
108
+
109
+ // Trying to find topmost link
110
+ while ( potentialLinks [ 0 ] ) {
111
+ const linkerKey = potentialLinks . splice ( 0 , 1 ) ;
112
+ const linker = root . collection . getLinker ( linkerKey ) ;
113
+ if ( linker ) {
114
+ return linker ;
115
+ }
116
+ }
117
+ }
118
+
119
+
93
120
/**
94
121
* @param body
95
122
* @param fieldName
@@ -102,13 +129,13 @@ export function addFieldNode(body, fieldName, root) {
102
129
let dotted = dotize . convert ( { [ fieldName ] : body } ) ;
103
130
_ . each ( dotted , ( value , key ) => {
104
131
// check for link
105
- const parts = key . split ( '.' ) ;
106
- const linkerKey = parts . slice ( 0 , 2 ) . join ( '.' ) ;
132
+ const linker = tryFindLink ( root , key ) ;
107
133
108
- const linker = root . collection . getLinker ( linkerKey ) ;
134
+ if ( linker && ! root . hasCollectionNode ( linker . linkName ) ) {
135
+ const path = linker . linkName . split ( '.' ) . slice ( 1 ) . join ( '.' ) ;
136
+ const subrootBody = dot . pick ( path , body ) ;
109
137
110
- if ( linker && ! root . hasCollectionNode ( linkerKey ) ) {
111
- const subroot = new CollectionNode ( linker . getLinkedCollection ( ) , body [ parts [ 1 ] ] , linkerKey ) ;
138
+ const subroot = new CollectionNode ( linker . getLinkedCollection ( ) , subrootBody , linker . linkName ) ;
112
139
// must be before adding linker because _shouldCleanStorage method
113
140
createNodes ( subroot ) ;
114
141
root . add ( subroot , linker ) ;
0 commit comments