用户个人资料照片

User Profile Photo

我做了一个登录注册系统。但是用户个人资料照片存在问题。如果用户不想添加个人资料照片,则该用户的个人资料照片将为空。但是我得到一个错误。

这是我 user.js

的个人资料部分
profile:{
type: String,
}

这是我注册的相关post路由

let user= new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
profile: req.file.path.replace(/^public/, '')
});

最后这是我的 register.pug:

.file-field.input-field(method="post")
.btn.grey
label Profile Photo
input(name='profile', type='file', enctype="multipart/form-data")

但是当我在没有选择任何个人资料照片的情况下提交时,出现以下错误:

(node:26436) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'path' of undefined

但为什么会这样?我已经将个人资料照片声明为不需要。那么,如果我不想上传个人资料照片,为什么它会搜索路径?

您可以在将 req.file 设置到用户对象之前验证是否存在,如果没有,则将其设置为空字符串

let user= new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
profile: req.file ? req.file.path.replace(/^public/, '') : ""
});