Node.js基于Sequelize实现多条件动态筛选数据的功能开发问题咨询
实现方案
核心思路
动态构建查询条件对象,仅将请求中实际传入的非空筛选字段加入where查询配置,即可支持任意单字段/多字段组合筛选。
修改后完整代码
const bcrypt = require('bcryptjs'); // 修正原代码拼写错误bycrypt→bcrypt const db = require('../../models') const Company = db.company const coDisplay = async (req, res) => { // 1. 取出所有可能的筛选参数 const { location, department, ctc_offered } = req.body; // 2. 动态构建where查询对象 const where = {}; // 仅当参数存在且非空时加入查询条件,可根据业务调整判断逻辑 if (location !== undefined && location !== null && location !== '') { where.location = location; } if (department !== undefined && department !== null && department !== '') { where.department = department; } if (ctc_offered !== undefined && ctc_offered !== null && ctc_offered !== '') { where.ctc_offered = ctc_offered; } Company.findAll({ where }) .then((company) => { // 修正原有逻辑问题:findAll永远返回数组,空数组也为truthy,需判断长度 if (company.length === 0) { return res.status(400).send({ status:"102", message: "company Not found." }); } res.status(200).send({ status:"VB100", company: company}); }) .catch((err) => { res.status(500).send({ message: err.message }); }); }; module.exports = { coDisplay };
补充说明
- 如果不需要过滤空字符串,可简化判断逻辑为
if (location) where.location = location,如果字段允许值为0这类假值,要对应调整判断规则 - 默认三个条件是同时满足的AND关系,如果需要OR关系,可以引入Sequelize的
Op.or操作符配置
内容的提问来源于stack exchange,提问作者Kirti Palve
相关产品推荐
相关产品推荐

