删除用户竞赛表单时触发TypeError:无法读取undefined的'schoolName'属性
解决Cannot read property 'schoolName' of undefined的问题
让我们一步步拆解你遇到的问题,以及对应的修复方案:
核心错误点分析
回调函数参数不匹配
Mongoose的findByIdAndRemove方法回调签名是(err, deletedDocument)——它只会返回错误对象和被删除的文档,并没有第三个user参数。你代码里写的function(err, competition, user)会导致user直接是undefined,自然就没法读取user.schoolName了。代码执行顺序逻辑错误
你在res.redirect('/dashboard')之后才定义output,但res.redirect会直接结束HTTP响应,后面的代码根本不会被执行。就算user能正常获取,这部分邮件内容也永远不会被处理。用户信息获取方式错误
既然你用了ensureAuthenticated中间件,当前登录用户的信息已经存在req.user对象里了,完全不需要从数据库操作的回调里去拿。
修正后的代码
// delete competition form router.get('/dashboard/users/forms/competition-form/delete/:id', ensureAuthenticated, (req, res, next) => { CompetitionForm.findByIdAndRemove(req.params.id, function(err, deletedForm) { // 先处理删除失败的情况 if (err) { req.flash('error_msg', 'Failed to delete competition form'); return res.redirect('/dashboard'); } // 从req.user获取当前登录用户的信息 const user = req.user; // 构建邮件内容 const output = ` <h3>Competition Form Deletion</h3> <p>Hello ${user.schoolName},</p> <p>We are emailing you to make you aware that your competition form has been deleted from our records!</p> <br> <p>- POL – Puerto Rico</p> `; // 这里添加你的邮件发送逻辑(比如用nodemailer) // 示例参考: // transporter.sendMail({ // from: 'your-service-email@example.com', // to: user.email, // subject: 'Your Competition Form Has Been Deleted', // html: output // }, (mailErr) => { // if (mailErr) { // req.flash('error_msg', 'Form deleted but notification email failed to send'); // } else { // req.flash('success_msg', 'Competition form removed successfully!'); // } // res.redirect('/dashboard'); // }); // 如果暂时不需要邮件发送,保留基础逻辑 req.flash('success_msg', 'The competition form removed successfully!'); res.redirect('/dashboard'); }); });
额外优化建议
推荐使用async/await语法替代回调,代码可读性会大幅提升:
router.get('/dashboard/users/forms/competition-form/delete/:id', ensureAuthenticated, async (req, res, next) => { try { const deletedForm = await CompetitionForm.findByIdAndRemove(req.params.id); if (!deletedForm) { req.flash('error_msg', 'Competition form not found'); return res.redirect('/dashboard'); } const user = req.user; const output = ` <h3>Competition Form Deletion</h3> <p>Hello ${user.schoolName},</p> <p>We are emailing you to make you aware that your competition form has been deleted from our records!</p> <br> <p>- POL – Puerto Rico</p> `; // 邮件发送逻辑... req.flash('success_msg', 'Competition form removed successfully!'); res.redirect('/dashboard'); } catch (err) { req.flash('error_msg', 'Failed to delete competition form'); res.redirect('/dashboard'); } });
内容的提问来源于stack exchange,提问作者user8331511
相关产品推荐
相关产品推荐

