@@ -14,7 +14,6 @@ const cleanUpSongs = (songs, album) => {
1414const getAlbum = async ( req , res ) => {
1515 try {
1616 const { name } = req . params ;
17- console . log ( name ) ;
1817 const album = await Album . findOne ( { title : name } )
1918 . select ( "-__v" )
2019 . select ( "-_id" )
@@ -58,6 +57,32 @@ const getAllAlbums = async (req, res) => {
5857 }
5958} ;
6059
60+ const searchAlbum = async ( req , res ) => {
61+ const { name } = req . query ;
62+
63+ try {
64+ // Use a regular expression to perform a case-insensitive search
65+ const albums = await Album . find ( { title : { $regex : name , $options : "i" } } )
66+ . select ( "-__v -_id" )
67+ . lean ( ) ;
68+
69+ for ( const album of albums ) {
70+ const songPromises = album . tracks . map ( ( songId ) =>
71+ Song . findById ( songId . toString ( ) ) . select ( "-__v" ) . select ( "-_id" ) . lean ( )
72+ ) ;
73+ const songs = await Promise . all ( songPromises ) ;
74+
75+ album . tracks = cleanUpSongs ( songs , album ) ;
76+ album . songs = album . tracks . length ;
77+ }
78+
79+ res . json ( albums ) ;
80+ } catch ( error ) {
81+ console . error ( "Error searching songs:" , error . message ) ;
82+ res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
83+ }
84+ } ;
85+
6186const deleteAlbum = async ( req , res ) => {
6287 try {
6388 const { id } = req . params ;
@@ -92,7 +117,6 @@ const newAlbum = async (req, res) => {
92117 const newAlbum = new Album ( {
93118 title,
94119 artist,
95- releaseYear,
96120 releaseDate,
97121 albumCover,
98122 tracks : [ ] ,
@@ -111,4 +135,5 @@ module.exports = {
111135 deleteAlbum,
112136 newAlbum,
113137 getAlbum,
138+ searchAlbum,
114139} ;
0 commit comments