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

如何在Sequelize查询对象中添加[op.and]条件?

Fixing Sequelize [Op.and] Condition Assignment Issue

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:

  1. Your name field assignment has an extra object wrapper (you wrote { name: inputName } instead of just inputName—that would make your where object have name: { name: inputName } instead of the desired name: inputName).
  2. You need to ensure you're using the correct Op.and reference 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 Op correctly, or used a lowercase op variable that wasn't defined.
  • While not directly breaking the Op.and assignment, the extra object wrapper on the name field would have caused unexpected query behavior.

内容的提问来源于stack exchange,提问作者lucbas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:57:53