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

如何在Sequelize raw query中使用用户输入替换参数

问题排查与修复方案

你的代码存在两个核心错误,修改后即可正常运行:

  • replacements 配置项格式错误
    Sequelize使用:xxx格式的命名占位符时,replacements要求传入对象,键名要和占位符名称一一对应。你当前直接传入term字符串变量,Sequelize无法匹配到:term占位符,需要将{ replacements: term, ... }修改为{ replacements: { term }, ... }。
  • 未引入QueryTypes
    直接使用QueryTypes.SELECT前需要先从Sequelize模块导入对应枚举,否则会报未定义错误。

修复后完整代码

// 顶部先引入QueryTypes,ES模块导入写法对应调整即可
const { QueryTypes } = require('sequelize');

router.get('/search', (req, res) => {
    let { term } = req.query;
    // 可选兜底逻辑:无搜索词时直接返回空结果,避免查询报错
    if (!term) {
        return res.render('locations', { locations: [] });
    }

    db.query(
        'SELECT * FROM locations WHERE code = :term',
        { replacements: { term }, raw: true, type: QueryTypes.SELECT})
        .then(locations => res.render('locations', { locations }))
        .catch(err => console.log(err));
})

内容的提问来源于stack exchange,提问作者jam-butter-scone-tea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:21:00