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

Node.js保存数据到MongoDB时,解决image参数可选的报错问题

解决Node.js上传图片非必填时的保存错误

问题核心很明确:当用户没选图片上传时,req.file会是undefined,你直接访问req.file.filename就会触发TypeError: Cannot read properties of undefined (reading 'filename')。虽然MongoDB的Schema已经把image设为非必填,但路由里的赋值逻辑没做判断。

只需要修改路由里的image字段赋值逻辑,先检查req.file是否存在,再决定是否传入filename:

修改后的路由代码

router.post("/", upload.single("image"), async (req, res) => {
  const post = new Post({
    title: req.body.title,
    category: req.body.category,
    content: req.body.content,
    video: req.body.video,
    // 仅当req.file存在时,才添加image字段
    ...(req.file && { image: req.file.filename })
  });
  try {
    const savedPost = await post.save();
    res.redirect("/");
  } catch (e) {
    console.log(e);
  }
});

另一种等价写法(用三元运算符)

如果你更习惯这种写法,也可以这样写:

router.post("/", upload.single("image"), async (req, res) => {
  const post = new Post({
    title: req.body.title,
    category: req.body.category,
    content: req.body.content,
    video: req.body.video,
    // 有图片时取filename,没有时设为undefined
    image: req.file ? req.file.filename : undefined
  });
  try {
    const savedPost = await post.save();
    res.redirect("/");
  } catch (e) {
    console.log(e);
  }
});

这两种写法都能实现需求:没有上传图片时,不会触发错误,MongoDB会正常保存其他字段的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:07:37