-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmovieController.ts
More file actions
1380 lines (1240 loc) · 35.5 KB
/
movieController.ts
File metadata and controls
1380 lines (1240 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Movie Controller
*
* This file contains all the business logic for movie operations.
* Each method demonstrates different MongoDB operations using the Node.js driver.
*
* Implemented operations:
* - insertOne() - Create a single movie
* - insertMany() - Create multiple movies
* - findOne() - Get a single movie by ID
* - find() - Get multiple movies with filtering and pagination
* - updateOne() - Update a single movie
* - updateMany() - Update multiple movies
* - deleteOne() - Delete a single movie
* - deleteMany() - Delete multiple movies
* - findOneAndDelete() - Find and delete a movie in one operation
*/
import { Request, Response } from "express";
import { ObjectId, Sort, Document } from "mongodb";
import { getCollection } from "../config/database";
import {
createErrorResponse,
createSuccessResponse,
validateRequiredFields,
} from "../utils/errorHandler";
import logger from "../utils/logger";
import {
CreateMovieRequest,
UpdateMovieRequest,
RawSearchQuery,
MovieFilter,
VectorSearchResult,
MovieWithCommentsResult,
SearchMoviesResponse,
RawMovieSearchQuery,
SearchPhrase,
AggregationComment,
VoyageAIResponse,
} from "../types";
/**
* GET /api/movies
*
* Retrieves multiple movies with optional filtering, sorting, and pagination.
* Demonstrates the find() operation with various query options.
*
* Query parameters:
* - q: Text search query (searches title, plot, fullplot)
* - genre: Filter by genre
* - year: Filter by year
* - minRating: Minimum IMDB rating
* - maxRating: Maximum IMDB rating
* - limit: Number of results (default: 20, max: 100)
* - skip: Number of documents to skip for pagination
* - sortBy: Field to sort by (default: title)
* - sortOrder: Sort direction - asc or desc (default: asc)
*/
export async function getAllMovies(req: Request, res: Response): Promise<void> {
const moviesCollection = getCollection("movies");
// Extract and validate query parameters
const {
q,
genre,
year,
minRating,
maxRating,
limit = "20",
skip = "0",
sortBy = "title",
sortOrder = "asc",
}: RawSearchQuery = req.query;
// Build MongoDB query filter
// This demonstrates how to construct complex queries with multiple conditions
const filter: MovieFilter = {};
// Text search by using MongoDB's text index
// This requires the text index we created in the database verification
if (q) {
filter.$text = { $search: q };
}
// Genre filtering
if (genre) {
filter.genres = { $regex: new RegExp(genre, "i") };
}
// Year filtering and validation
// The sample_mflix dataset only contains movies up to 2015
const MAX_DATASET_YEAR = 2015;
const MIN_VALID_YEAR = 1800;
let yearWarning: string | undefined;
if (year) {
const yearNum = parseInt(year);
// Validate year is within reasonable bounds
if (yearNum < MIN_VALID_YEAR) {
res.status(400).json(
createErrorResponse(
`Invalid year: ${yearNum}. Year must be ${MIN_VALID_YEAR} or later.`,
"INVALID_YEAR"
)
);
return;
}
// Warn if searching for years beyond the dataset's range
if (yearNum > MAX_DATASET_YEAR) {
yearWarning = `Note: The sample_mflix dataset only contains movies up to ${MAX_DATASET_YEAR}. Your search for year ${yearNum} may return no results.`;
}
filter.year = yearNum;
}
// Rating range filtering
// Demonstrates nested field queries (imdb.rating)
if (minRating || maxRating) {
filter["imdb.rating"] = {};
if (minRating) {
filter["imdb.rating"].$gte = parseFloat(minRating);
}
if (maxRating) {
filter["imdb.rating"].$lte = parseFloat(maxRating);
}
}
// Parse and validate pagination parms for invalid inputs
const limitNum = Math.min(
Math.max(
parseInt(limit) || 20, // Default to 20 if invalid
1 // Min 1 result
),
100 // Cap at 100 results for performance
);
const skipNum = Math.max(
parseInt(skip) || 0, // Default to 0 if invalid
0 // skip must be positive number
);
// Build sort object
// Demonstrates dynamic sorting based on user input
const sort: Sort = {
[sortBy]: sortOrder === "desc" ? -1 : 1,
};
// Execute the find operation with all options
const movies = await moviesCollection
.find(filter)
.sort(sort)
.limit(limitNum)
.skip(skipNum)
.toArray();
// Build response message, including year warning if applicable
let message = `Found ${movies.length} movies`;
if (yearWarning) {
message = `${message}. ${yearWarning}`;
}
// Return successful response
res.json(createSuccessResponse(movies, message));
}
/**
* GET /api/movies/genres
*
* Retrieves all unique genres from the movies collection.
* Demonstrates the distinct() operation.
*
* Returns an array of unique genre strings, sorted alphabetically.
*/
export async function getDistinctGenres(
req: Request,
res: Response
): Promise<void> {
const moviesCollection = getCollection("movies");
// Use distinct() to get all unique values from the genres array field
// MongoDB automatically flattens array fields when using distinct()
const genres = await moviesCollection.distinct("genres");
// Filter out null/empty values and sort alphabetically
const validGenres = genres
.filter((genre): genre is string => typeof genre === "string" && genre.length > 0)
.sort((a, b) => a.localeCompare(b));
res.json(
createSuccessResponse(validGenres, `Found ${validGenres.length} distinct genres`)
);
}
/**
* GET /api/movies/:id
*
* Retrieves a single movie by its ObjectId.
* Demonstrates the findOne() operation.
*/
export async function getMovieById(req: Request, res: Response): Promise<void> {
const { id } = req.params;
// Validate ObjectId format
if (!ObjectId.isValid(id)) {
res
.status(400)
.json(
createErrorResponse("Invalid movie ID format", "INVALID_OBJECT_ID")
);
return;
}
const moviesCollection = getCollection("movies");
// Use findOne() to get a single document by _id
const movie = await moviesCollection.findOne({ _id: new ObjectId(id) });
if (!movie) {
res
.status(404)
.json(createErrorResponse("Movie not found", "MOVIE_NOT_FOUND"));
return;
}
res.json(createSuccessResponse(movie, "Movie retrieved successfully"));
}
/**
* POST /api/movies
*
* Creates a single new movie document.
* Demonstrates the insertOne() operation.
*/
export async function createMovie(req: Request, res: Response): Promise<void> {
const movieData: CreateMovieRequest = req.body;
// Validate required fields
// The title field is the minimum requirement for a movie
validateRequiredFields(movieData, ["title"]);
const moviesCollection = getCollection("movies");
// Use insertOne() to create a single document
// This operation returns information about the insertion including the new _id
const result = await moviesCollection.insertOne(movieData);
if (!result.acknowledged) {
throw new Error("Movie insertion was not acknowledged by the database");
}
// Retrieve the created document to return complete data
const createdMovie = await moviesCollection.findOne({
_id: result.insertedId,
});
res
.status(201)
.json(
createSuccessResponse(
createdMovie,
`Movie '${movieData.title}' created successfully`
)
);
}
/**
* POST /api/movies/batch
*
* Creates multiple movie documents in a single operation.
* Demonstrates the insertMany() operation.
*/
export async function createMoviesBatch(
req: Request,
res: Response
): Promise<void> {
const moviesData: CreateMovieRequest[] = req.body;
// Validate that we have an array of movies
if (!Array.isArray(moviesData) || moviesData.length === 0) {
res
.status(400)
.json(
createErrorResponse(
"Request body must be a non-empty array of movie objects",
"INVALID_INPUT"
)
);
return;
}
// Validate each movie has required fields
moviesData.forEach((movie, index) => {
try {
validateRequiredFields(movie, ["title"]);
} catch (error) {
throw new Error(
`Movie at index ${index}: ${
error instanceof Error ? error.message : "Unknown error"
}`
);
}
});
const moviesCollection = getCollection("movies");
// Use insertMany() to create multiple documents
const result = await moviesCollection.insertMany(moviesData);
if (!result.acknowledged) {
throw new Error(
"Batch movie insertion was not acknowledged by the database"
);
}
res.status(201).json(
createSuccessResponse(
{
insertedCount: result.insertedCount,
insertedIds: result.insertedIds,
},
`Successfully created ${result.insertedCount} movies`
)
);
}
/**
* PATCH /api/movies/:id
*
* Updates a single movie document.
* Demonstrates the updateOne() operation.
*/
export async function updateMovie(req: Request, res: Response): Promise<void> {
const { id } = req.params;
const updateData: UpdateMovieRequest = req.body;
// Validate ObjectId format
if (!ObjectId.isValid(id)) {
res
.status(400)
.json(
createErrorResponse("Invalid movie ID format", "INVALID_OBJECT_ID")
);
return;
}
// Ensure we have something to update
if (Object.keys(updateData).length === 0) {
res
.status(400)
.json(createErrorResponse("No update data provided", "NO_UPDATE_DATA"));
return;
}
const moviesCollection = getCollection("movies");
// Use updateOne() to update a single document
// $set operator replaces the value of fields with specified values
const result = await moviesCollection.updateOne(
{ _id: new ObjectId(id) },
{ $set: updateData }
);
if (result.matchedCount === 0) {
res
.status(404)
.json(createErrorResponse("Movie not found", "MOVIE_NOT_FOUND"));
return;
}
// Retrieve the updated document to return complete data
const updatedMovie = await moviesCollection.findOne({
_id: new ObjectId(id),
});
res.json(
createSuccessResponse(
updatedMovie,
`Movie updated successfully. Modified ${result.modifiedCount} field(s).`
)
);
}
/**
* PATCH /api/movies
*
* Updates multiple movies based on a filter.
* Demonstrates the updateMany() operation.
*/
export async function updateMoviesBatch(
req: Request,
res: Response
): Promise<void> {
const { filter, update } = req.body;
// Validate input
if (!filter || !update) {
res
.status(400)
.json(
createErrorResponse(
"Both filter and update objects are required",
"MISSING_REQUIRED_FIELDS"
)
);
return;
}
if (Object.keys(update).length === 0) {
res
.status(400)
.json(
createErrorResponse("Update object cannot be empty", "EMPTY_UPDATE")
);
return;
}
const moviesCollection = getCollection("movies");
// Handle ObjectId conversion for _id fields in $in queries
let processedFilter = { ...filter };
if (filter._id && filter._id.$in && Array.isArray(filter._id.$in)) {
// Convert string IDs to ObjectId instances
processedFilter._id = {
$in: filter._id.$in.map((id: string) => {
if (ObjectId.isValid(id)) {
return new ObjectId(id);
}
throw new Error(`Invalid ObjectId: ${id}`);
})
};
}
// Use updateMany() to update multiple documents
// This is useful for bulk operations like updating all movies from a certain year
const result = await moviesCollection.updateMany(processedFilter, { $set: update });
res.json(
createSuccessResponse(
{
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
},
`Update operation completed. Matched ${result.matchedCount} documents, modified ${result.modifiedCount} documents.`
)
);
}
/**
* DELETE /api/movies/:id
*
* Deletes a single movie document.
* Demonstrates the deleteOne() operation.
*/
export async function deleteMovie(req: Request, res: Response): Promise<void> {
const { id } = req.params;
// Validate ObjectId format
if (!ObjectId.isValid(id)) {
res
.status(400)
.json(
createErrorResponse("Invalid movie ID format", "INVALID_OBJECT_ID")
);
return;
}
const moviesCollection = getCollection("movies");
// Use deleteOne() to remove a single document
const result = await moviesCollection.deleteOne({ _id: new ObjectId(id) });
if (result.deletedCount === 0) {
res
.status(404)
.json(createErrorResponse("Movie not found", "MOVIE_NOT_FOUND"));
return;
}
res.json(
createSuccessResponse(
{ deletedCount: result.deletedCount },
"Movie deleted successfully"
)
);
}
/**
* DELETE /api/movies
*
* Deletes multiple movies based on a filter.
* Demonstrates the deleteMany() operation.
*/
export async function deleteMoviesBatch(
req: Request,
res: Response
): Promise<void> {
const { filter } = req.body;
// Validate input
if (!filter || Object.keys(filter).length === 0) {
res
.status(400)
.json(
createErrorResponse(
"Filter object is required and cannot be empty. This prevents accidental deletion of all documents.",
"MISSING_FILTER"
)
);
return;
}
const moviesCollection = getCollection("movies");
// Handle ObjectId conversion for _id fields in $in queries
let processedFilter = { ...filter };
if (filter._id && filter._id.$in && Array.isArray(filter._id.$in)) {
// Convert string IDs to ObjectId instances
processedFilter._id = {
$in: filter._id.$in.map((id: string) => {
if (ObjectId.isValid(id)) {
return new ObjectId(id);
}
throw new Error(`Invalid ObjectId: ${id}`);
})
};
}
// Use deleteMany() to remove multiple documents
// This operation is useful for cleanup tasks like removing all movies from a certain year
const result = await moviesCollection.deleteMany(processedFilter);
res.json(
createSuccessResponse(
{ deletedCount: result.deletedCount },
`Delete operation completed. Removed ${result.deletedCount} documents.`
)
);
}
/**
* DELETE /api/movies/:id/find-and-delete
*
* Finds and deletes a movie in a single atomic operation.
* Demonstrates the findOneAndDelete() operation.
*/
export async function findAndDeleteMovie(
req: Request,
res: Response
): Promise<void> {
const { id } = req.params;
// Validate ObjectId format
if (!ObjectId.isValid(id)) {
res
.status(400)
.json(
createErrorResponse("Invalid movie ID format", "INVALID_OBJECT_ID")
);
return;
}
const moviesCollection = getCollection("movies");
// Use findOneAndDelete() to find and delete in a single atomic operation
// This is useful when you need to return the deleted document
// or ensure the document exists before deletion
const deletedMovie = await moviesCollection.findOneAndDelete({
_id: new ObjectId(id),
});
if (!deletedMovie) {
res
.status(404)
.json(createErrorResponse("Movie not found", "MOVIE_NOT_FOUND"));
return;
}
res.json(
createSuccessResponse(deletedMovie, "Movie found and deleted successfully")
);
}
/**
* GET /api/movies/search
*
* Search movies using MongoDB Search across multiple fields.
* Demonstrates MongoDB Search with compound queries.
*/
export async function searchMovies(req: Request, res: Response): Promise<void> {
const moviesCollection = getCollection("movies");
const {
plot,
fullplot,
directors,
writers,
cast,
limit = "20",
skip = "0",
searchOperator = "must",
}: RawMovieSearchQuery = req.query;
// Validate search operator
const validOperators = ["must", "should", "mustNot", "filter"];
if (!validOperators.includes(searchOperator)) {
res
.status(400)
.json(
createErrorResponse(
`Invalid search_operator '${searchOperator}'. Must be one of: ${validOperators.join(", ")}`,
"INVALID_SEARCH_OPERATOR"
)
);
return;
}
// Build search phrases array
const searchPhrases: SearchPhrase[] = [];
if (plot) {
searchPhrases.push({
phrase: {
query: plot,
path: "plot",
},
});
}
if (fullplot) {
searchPhrases.push({
phrase: {
query: fullplot,
path: "fullplot",
},
});
}
// Use compound operator with "should" clauses to create a scoring hierarchy:
// 1. phrase match (highest score) - exact phrase in same array element
// 2. text match without fuzzy (high score) - all terms present, exact spelling
// 3. text match with fuzzy (lower score) - typo-tolerant fallback; update fuzzy settings as needed
// For more details, see: https://www.mongodb.com/docs/atlas/atlas-search/operators-collectors/text/
if (directors) {
searchPhrases.push({
compound: {
should: [
// Highest score: exact phrase match
{ phrase: { query: directors, path: "directors" } },
// High score: exact text match (all terms, no fuzzy)
{ text: { query: directors, path: "directors", matchCriteria: "all" } },
// Lower score: fuzzy match (typo tolerance)
{
text: {
query: directors,
path: "directors",
matchCriteria: "all",
fuzzy: { maxEdits: 1, prefixLength: 2 }, // Allow up to 1 edit, require first 2 characters to match
},
},
],
minimumShouldMatch: 1,
},
});
}
if (writers) {
// See comments above regarding compound scoring hierarchy.
searchPhrases.push({
compound: {
should: [
{ phrase: { query: writers, path: "writers" } },
{ text: { query: writers, path: "writers", matchCriteria: "all" } },
{
text: {
query: writers,
path: "writers",
matchCriteria: "all",
fuzzy: { maxEdits: 1, prefixLength: 2 },
},
},
],
minimumShouldMatch: 1,
},
});
}
if (cast) {
// See comments above regarding compound scoring hierarchy.
searchPhrases.push({
compound: {
should: [
{ phrase: { query: cast, path: "cast" } },
{ text: { query: cast, path: "cast", matchCriteria: "all" } },
{
text: {
query: cast,
path: "cast",
matchCriteria: "all",
fuzzy: { maxEdits: 1, prefixLength: 2 },
},
},
],
minimumShouldMatch: 1,
},
});
}
if (searchPhrases.length === 0) {
res
.status(400)
.json(
createErrorResponse(
"At least one search parameter must be provided",
"NO_SEARCH_PARAMETERS"
)
);
return;
}
// Parse pagination parameters
const limitNum = Math.min(Math.max(parseInt(limit) || 20, 1), 100);
const skipNum = Math.max(parseInt(skip) || 0, 0);
// Build aggregation pipeline
const pipeline = [
{
$search: {
index: "movieSearchIndex",
compound: {
[searchOperator]: searchPhrases,
},
},
},
{
$facet: {
totalCount: [{ $count: "count" }],
results: [
{ $skip: skipNum },
{ $limit: limitNum },
{
$project: {
_id: 1,
title: 1,
year: 1,
plot: 1,
fullplot: 1,
released: 1,
runtime: 1,
poster: 1,
genres: 1,
directors: 1,
writers: 1,
cast: 1,
countries: 1,
languages: 1,
rated: 1,
awards: 1,
imdb: 1,
},
},
],
},
},
];
const results = await moviesCollection.aggregate(pipeline).toArray();
const facetResult = results[0] || {};
const totalCount = facetResult.totalCount?.[0]?.count || 0;
const movies = facetResult.results || [];
const response: SearchMoviesResponse = {
movies,
totalCount,
};
res.json(
createSuccessResponse(
response,
`Found ${totalCount} movies matching the search criteria`
)
);
}
/**
* GET /api/movies/vector-search
*
* Search movies using MongoDB Vector Search for semantic similarity.
* Demonstrates vector search using embeddings to find similar plots.
*/
export async function vectorSearchMovies(req: Request, res: Response): Promise<void> {
const { q, limit = "10" } = req.query;
// Validate query parameter
if (!q || typeof q !== "string" || q.trim().length === 0) {
res
.status(400)
.json(
createErrorResponse(
"Search query is required",
"MISSING_QUERY_PARAMETER"
)
);
return;
}
// Check if Voyage AI API key is configured
if (!process.env.VOYAGE_API_KEY || process.env.VOYAGE_API_KEY.trim().length === 0) {
res
.status(400)
.json(
createErrorResponse(
"Vector search unavailable: VOYAGE_API_KEY not configured. Please add your API key to the .env file",
"SERVICE_UNAVAILABLE"
)
);
return;
}
// Validate and set limit (default: 20, min: 1, max: 50)
const limitNum = Math.min(Math.max(parseInt(limit as string) || 20, 1), 50);
try {
// Generate embedding using Voyage AI REST API
const queryVector = await generateVoyageEmbedding(q.trim(), process.env.VOYAGE_API_KEY);
// Get embedded movies collection for vector search
const embeddedMoviesCollection = getCollection("embedded_movies");
// Step 1: Build the $vectorSearch aggregation pipeline for embedded_movies
const vectorSearchPipeline = [
{
$vectorSearch: {
index: "vector_index",
path: "plot_embedding_voyage_3_large",
queryVector: queryVector,
numCandidates: limitNum * 20, // We recommend searching 20 times higher than the limit to improve result relevance
limit: limitNum,
},
},
{
$project: {
_id: 1,
score: { $meta: "vectorSearchScore" },
},
},
];
// Execute vector search to get movie IDs and scores
const vectorResults = await embeddedMoviesCollection.aggregate(vectorSearchPipeline).toArray();
if (vectorResults.length === 0) {
res.json(
createSuccessResponse(
[],
`No similar movies found for query: '${q}'`
)
);
return;
}
// Extract movie IDs and create score mapping
const movieIds = vectorResults.map(doc => doc._id);
const scoreMap = new Map();
vectorResults.forEach(doc => {
scoreMap.set(doc._id.toString(), doc.score);
});
// Step 2: Fetch complete movie data from the movies collection
const moviesCollection = getCollection("movies");
// Build aggregation pipeline to safely handle year field and get complete movie data
const moviesPipeline = [
{
$match: {
_id: { $in: movieIds }
}
},
{
$project: {
_id: 1,
title: 1,
plot: 1,
poster: 1,
genres: 1,
directors: 1,
cast: 1,
// Safely convert year to integer, handling strings and dirty data
year: {
$cond: {
if: {
$and: [
{ $ne: ["$year", null] },
{ $eq: [{ $type: "$year" }, "int"] }
]
},
then: "$year",
else: null
}
}
}
}
];
const movieResults = await moviesCollection.aggregate(moviesPipeline).toArray();
// Step 3: Combine movie data with vector search scores
const finalResults: VectorSearchResult[] = movieResults.map(movie => {
const movieIdStr = movie._id.toString();
const score = scoreMap.get(movieIdStr) || 0;
return {
_id: movieIdStr,
title: movie.title || '',
plot: movie.plot,
poster: movie.poster,
year: movie.year,
genres: movie.genres || [],
directors: movie.directors || [],
cast: movie.cast || [],
score: score,
};
});
// Sort results by score (highest first) to maintain relevance order
finalResults.sort((a, b) => b.score - a.score);
res.json(
createSuccessResponse(
finalResults,
`Found ${finalResults.length} similar movies for query: '${q}'`
)
);
} catch (error) {
logger.error("Vector search error:", error);
// Handle Voyage AI authentication errors
if (error instanceof VoyageAuthError) {
res
.status(401)
.json(
createErrorResponse(
error.message,
"VOYAGE_AUTH_ERROR",
"Please verify your VOYAGE_API_KEY is correct in the .env file"
)
);
return;
}
// Handle other Voyage AI API errors
if (error instanceof VoyageAPIError) {
res
.status(503)
.json(
createErrorResponse(
"Vector search service unavailable",
"VOYAGE_API_ERROR",
error.message
)
);
return;
}
// Handle generic errors
res
.status(500)
.json(
createErrorResponse(
"Error performing vector search",
"VECTOR_SEARCH_ERROR",
error instanceof Error ? error.message : "Unknown error"
)
);
}
}
/**
* GET /api/movies/aggregations/reportingByComments
*
* Aggregate movies with their most recent comments.
* Demonstrates MongoDB $lookup aggregation to join collections.
*/
export async function getMoviesWithMostRecentComments(
req: Request,
res: Response
): Promise<void> {
const moviesCollection = getCollection("movies");
const { limit = "10", movieId } = req.query;
const limitNum = Math.min(Math.max(parseInt(limit as string) || 10, 1), 50);
// Build aggregation pipeline
const pipeline: Document[] = [
// STAGE 1: Initial filter for data quality - filters bad data in
// the collection
{
$match: {
year: { $type: "number", $gte: 1800, $lte: 2030 },
},