@@ -67,9 +67,44 @@ const projectSchema = new mongoose.Schema(
6767
6868projectSchema . index ( { technologies : 1 } ) ;
6969
70+ const normalizeImages = ( value ) => {
71+ if ( ! value ) return [ ] ;
72+ const list = Array . isArray ( value ) ? value : [ value ] ;
73+ return list
74+ . map ( ( item ) => {
75+ if ( typeof item === "string" ) return item . trim ( ) ;
76+ if ( item ?. url ) return String ( item . url ) . trim ( ) ;
77+ if ( item ?. value ) return String ( item . value ) . trim ( ) ;
78+ return "" ;
79+ } )
80+ . filter ( Boolean ) ;
81+ } ;
82+
83+ const normalizeIdList = ( value ) => {
84+ if ( ! Array . isArray ( value ) ) return [ ] ;
85+ return value . filter ( ( id ) => mongoose . isValidObjectId ( id ) ) ;
86+ } ;
87+
7088projectSchema . pre ( "validate" , function ( next ) {
7189 const imagesModified = this . isModified ( "images" ) ;
7290 const imageModified = this . isModified ( "image" ) ;
91+ const categoryModified = this . isModified ( "category" ) ;
92+ const technologiesModified = this . isModified ( "technologies" ) ;
93+
94+ if ( imagesModified ) {
95+ this . images = normalizeImages ( this . images ) ;
96+ }
97+ if ( imageModified && typeof this . image === "string" ) {
98+ this . image = this . image . trim ( ) ;
99+ }
100+ if ( categoryModified && this . category ) {
101+ if ( ! mongoose . isValidObjectId ( this . category ) ) {
102+ this . category = undefined ;
103+ }
104+ }
105+ if ( technologiesModified ) {
106+ this . technologies = normalizeIdList ( this . technologies ) ;
107+ }
73108
74109 if ( imagesModified ) {
75110 if ( Array . isArray ( this . images ) && this . images . length ) {
0 commit comments