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

博客点赞功能集成失败,遇TypeError错误寻求解决

博客点赞功能故障排查与修复

问题分析

当前出现的TypeError: Cannot read properties of null (reading 'postTitle')错误,核心原因有两点:

  1. 代码中存在拼写错误:foundUser.post.id(postId)应为foundUser.posts.id(postId)(User模型中存储文章的字段是复数posts数组,与查询条件"posts._id"对应),这直接导致post变量为null。
  2. 空值判断逻辑不完善:当post为null时,仅执行重定向但未终止函数,后续代码仍尝试访问post.postTitle引发报错。

同时原代码未实现取消点赞逻辑,且点赞添加逻辑因拼写错误无法正常工作。

修复步骤与完整代码

1. 修正拼写错误与空值判断

将foundUser.post.id(postId)改为foundUser.posts.id(postId),并在空值判断后添加return终止函数执行,避免后续代码报错。

2. 完善点赞/取消点赞逻辑

通过indexOf判断用户是否已点赞,存在则执行移除(取消点赞),不存在则添加userId到点赞数组,同时补充数据库保存的错误处理。

修复后的完整代码:

app.post("/post/:postId", function (req, res) {
  const postId = req.params.postId;
  const userId = req.user.id;

  User.findOne({ "posts._id": postId }, function (err, foundUser) {
    if (err) {
      console.log(err);
      return res.redirect('/');
    }
    // 检查是否找到对应用户
    if (!foundUser) {
      return res.redirect('/');
    }
    // 修正posts字段拼写错误
    const post = foundUser.posts.id(postId);
    if(!post){
      return res.redirect('/')
    }
    const likeIndex = post.likes.indexOf(userId);
    if (likeIndex !== -1) {
      // 已点赞,执行取消操作
      post.likes.splice(likeIndex, 1);
    } else {
      // 未点赞,添加用户id到点赞数组
      post.likes.push(userId);
    }
    foundUser.save(function (saveErr) {
      if (saveErr) {
        console.log(saveErr);
        return res.redirect('/');
      }
      res.redirect("/post/" + encodeURIComponent(post.postTitle));
    });
  });
});

额外优化说明

  • 增加了foundUser的空值判断,避免查询不到用户时后续代码报错
  • 用indexOf替代includes,方便后续执行移除操作(兼容更多场景)
  • 补充了数据库保存操作的错误处理,避免保存失败时无响应
  • 完整实现了点赞/取消点赞的双向逻辑

内容的提问来源于stack exchange,提问作者Dare Ace Rex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:35:11