<p>最近我参加了一次工作面试,然后我得到了一点作业。然后我收到了反馈,说我的更新端点中有不必要的查询和事务组合。</p>
<pre class="brush:php;toolbar:false;">export const update = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const reportId = parseInt(req.params.id)
        const { name, age, info } = req.body
        const report = await ReportModel.findOne({
            where: {
                id: reportId
            }
        })
        if (!report) return next(new EntityNotExistError("报告不存在"))
        await ReportModel.update({
            name,
            age,
            info
        }, {
            where: {
                id: reportId
            }
        })
        const _report = await ReportModel.findOne({
            where: {
                id: reportId
            }
        })
        return res.json({
            message: "报告编辑成功",
            report: _report
        })
    } catch (error) {
        return next(error)
    }
}</pre>
<p>正如你所看到的,第一个查询检查实体是否存在,然后我对实体进行更新,最后一个查询返回更新后的实体。
有没有一些方法可以优化与数据库的通信?</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
您的代码涉及到对数据库的三个不同交互,用于单个更新操作:
ReportModel.findOne()ReportModel.update()ReportModel.findOne()减少数据库查询可以完成任务并提高性能。
**您修复后的代码:**
export const update = async(req: Request, res: Response, next: NextFunction) => { try { const reportId = parseInt(req.params.id); const { name, age, info } = req.body; // 执行更新并获取受影响的行数 const [numberOfAffectedRows] = await ReportModel.update({ name, age, info }, { where: { id: reportId }, // 此标志检查更新函数是否返回更新后的对象 returning: true }); // 检查实体是否被找到和更新 if (numberOfAffectedRows === 0) { return next(new EntityNotExistError("报告不存在")); } // 获取更新后的报告 const updatedReport = await ReportModel.findOne({ where: { id: reportId } }); return res.json({ message: "报告已成功编辑", report: updatedReport }); } catch (error) { return next(error); } }