注册系统未传头像报错求助:TypeError: Cannot read property 'path' of undefined
Hey there, let's break down why this error is happening and get your optional avatar feature working as expected!
The Root Cause
Even though you've set the profile field as non-required in your Mongoose schema, the error isn't coming from database validation—it's from your route code. When a user skips uploading an avatar, req.file becomes undefined (since no file was sent with the request). Your code tries to access req.file.path directly without checking if req.file exists first, which triggers the TypeError.
Step-by-Step Solutions
Add a Check for
req.filein Your Route
Modify your User instance creation logic to handle the case where no file is uploaded. Use a ternary operator to setprofileto the file path (if it exists) ornull(if it doesn't):let user = new User({ username: req.body.username, email: req.body.email, password: hashedPassword, profile: req.file ? req.file.path.replace(/^public/, '') : null });This ensures you never try to access
pathon an undefinedreq.file.Explicitly Allow Null in Your Mongoose Schema (Optional but Clear)
While Mongoose allowsnullfor string fields by default, making this explicit in your schema clarifies your intent and avoids future confusion:profile: { type: String, default: null }Now if no avatar is provided, the
profilefield will automatically default tonullin the database.Fix the
enctypePlacement in Your Pug Template
You currently have theenctype="multipart/form-data"attribute on the file input, but this needs to be on the<form>tag instead—otherwise, file uploads won't work correctly. Update your template:form(method="post" enctype="multipart/form-data") .file-field.input-field .btn.grey label Profile Photo input(name='profile', type='file')This is a critical fix for ensuring file uploads function properly when users do choose to upload an avatar.
Why This Works
By checking if req.file exists before accessing its properties, you eliminate the TypeError entirely. The schema adjustment makes your data model more explicit, and fixing the enctype ensures file uploads work as intended when users provide an avatar.
内容的提问来源于stack exchange,提问作者İ. ALP EREN GÜL

