如何在Sequelize查询对象中添加[op.and]条件?
Hey there, let's get your [Op.and] condition working properly! I see where you might be tripping up—let's break down the fixes step by step.
First, Check Your Op Import
The most common culprit here is not importing Sequelize operators correctly. Make sure you're pulling in Op from the sequelize package at the top of your file:
// CommonJS const { Op } = require('sequelize'); // ES6 Modules import { Op } from 'sequelize';
If you're using a lowercase op variable instead of Op, that's definitely going to break things—Sequelize exports operators under the uppercase Op object by default.
Fix the Assignment Syntax (and a Small Name Field Bug)
Looking at your code, there are two tiny issues to correct:
- Your
namefield assignment has an extra object wrapper (you wrote{ name: inputName }instead of justinputName—that would make yourwhereobject havename: { name: inputName }instead of the desiredname: inputName). - You need to ensure you're using the correct
Op.andreference in bracket notation.
Here's the corrected code that will generate your desired query object:
const { Op } = require('sequelize'); let query = { where: { id: 5 } }; if (inputName) { // Fix: Assign inputName directly instead of wrapping it in an object query.where.name = inputName; } if (inputType) { // Correctly assign the Op.and condition using bracket notation query.where[Op.and] = [ { type1: inputType }, { type2: inputType } ]; } Model.findAll(query);
This will produce exactly the query object you want:
{ where: { id: 5, name: inputName, [Op.and]: [ { type1: inputType }, { type2: inputType } ] } }
Bonus: Append to Existing [Op.and] Conditions
If you ever need to add more conditions to an existing Op.and array (instead of overwriting it), use this approach to avoid losing existing rules:
if (inputType) { // Initialize the Op.and array if it doesn't exist yet if (!query.where[Op.and]) { query.where[Op.and] = []; } // Push new conditions to the array query.where[Op.and].push({ type1: inputType }, { type2: inputType }); }
Why Your Original Code Failed
Chances are it was one of two issues:
- You didn't import
Opcorrectly, or used a lowercaseopvariable that wasn't defined. - While not directly breaking the
Op.andassignment, the extra object wrapper on thenamefield would have caused unexpected query behavior.
内容的提问来源于stack exchange,提问作者lucbas

