You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EJS中如何设置if-else条件判断用户头像是否存在并解决相关报错

问题错误点

  1. 判断属性选择错误:你在Schema中定义的profile是对象类型,不是数组,不存在length属性,user.profile.length > 0的判断永远返回false,所以无论用户有没有上传头像都会进入else分支,未上传头像时profile为空,自然取不到data属性调用toString方法。
  2. 判断分支逻辑写反:你当前的代码逻辑是if条件成立时渲染默认头像,else渲染自定义头像,和你需要的「有头像渲染自定义、无头像渲染默认」的逻辑完全相反。
  3. 缺少字段完整性校验:即使profile对象存在,也可能出现data字段为空的情况,直接调用toString依然会报错。

修复方案

直接修改EJS模板中的判断逻辑,先校验profile和其下的data字段都存在,再渲染自定义头像,否则走默认头像分支,代码如下:

<% if (user.profile && user.profile.data) { %>
    <!-- 用户上传的头像,用户更新头像后赋值 -->
    <img src="data:image/<%=user.profile.contentType%>;base64,<%=user.profile.data.toString('base64')%>" alt="">
<% } else { %>
    <!-- 默认头像 -->
    <img src="css/image/user.svg" alt="">
<% } %>

可选优化

如果想从源头避免空值问题,可以在mongoose的Schema中给profile设置默认值:

const userSchema = new mongoose.Schema({
    name: String ,
    email:String,
    password:String,
    profile:{ 
        data: Buffer, 
        contentType: String,
        default: () => ({}) // 新增默认空对象
    }
});

内容的提问来源于stack exchange,提问作者Tushar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:21:03