@@ -207,22 +207,7 @@ class CountryQueryService {
207207 });
208208 }
209209
210- // --- Stage 4: Project to original Country structure and ensure uniqueness ---
211- // After lookups and matches, we might have duplicate countries if they
212- // matched multiple sources/headlines. We need to group them back to unique countries.
213- pipeline.add ({
214- r'$group' : {
215- '_id' : r'$_id' , // Group by the original country ID
216- 'doc' : {r'$first' : r'$$ROOT' }, // Take the first full document
217- },
218- });
219- pipeline.add ({
220- r'$replaceRoot' : {
221- 'newRoot' : r'$doc' , // Replace root with the original document
222- },
223- });
224-
225- // --- Stage 5: Sorting ---
210+ // --- Stage 4: Sorting ---
226211 if (sort != null && sort.isNotEmpty) {
227212 final sortStage = < String , dynamic > {};
228213 for (final option in sort) {
@@ -231,7 +216,7 @@ class CountryQueryService {
231216 pipeline.add ({r'$sort' : sortStage});
232217 }
233218
234- // --- Stage 6 : Pagination (Skip and Limit) ---
219+ // --- Stage 5 : Pagination (Skip and Limit) ---
235220 if (pagination? .cursor != null ) {
236221 // For cursor-based pagination, we'd typically need a more complex
237222 // aggregation that sorts by the cursor field and then skips.
@@ -247,9 +232,11 @@ class CountryQueryService {
247232 pipeline.add ({r'$limit' : pagination! .limit! + 1 });
248233 }
249234
250- // --- Stage 7: Final Projection ---
251- // Project to match the Country model's JSON structure if necessary
252- // (e.g., if _id was used, map it back to id)
235+ // --- Stage 6: Final Projection ---
236+ // Project to match the Country model's JSON structure.
237+ // The $lookup stages add fields ('matchingSources', 'matchingHeadlines')
238+ // that are not part of the Country model, so we project only the fields
239+ // that are part of the model to ensure clean deserialization.
253240 pipeline.add ({
254241 r'$project' : {
255242 '_id' : 0 , // Exclude _id
@@ -260,7 +247,6 @@ class CountryQueryService {
260247 'createdAt' : r'$createdAt' ,
261248 'updatedAt' : r'$updatedAt' ,
262249 'status' : r'$status' ,
263- // Ensure other fields are projected if they were modified or needed
264250 },
265251 });
266252
0 commit comments