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

如何在Dexie.js的where子句中使用两个相等条件查询?

Dexie.js 多条件AND查询的正确实现

你的代码问题出在.and()方法的使用上——.and()需要接收一个回调函数来定义第二个条件,而不是直接传入字段名。以下是两种可行的解决方法:

方法1:使用.and()回调函数

直接修正你的代码,把.and("gender")改成回调函数判断gender字段:

db.tab.where("age").equals(20)
  .and(item => item.gender === 'Male')
  .toArray()
  .then(items => {
    // 处理查询结果
    console.log(items);
  })
  .catch(error => {
    // 捕获错误
    console.error(error);
  });

方法2:使用复合索引(推荐,性能更优)

如果这类多条件查询是高频操作,建议先给表创建age+gender的复合索引,再通过复合索引查询:

1. 定义表时添加复合索引

const db = new Dexie('yourDatabaseName');
db.version(1).stores({
  tab: 'id, [age+gender]' // id为主键,[age+gender]是复合索引
});

2. 通过复合索引执行查询

db.tab.where('[age+gender]')
  .equals([20, 'Male'])
  .toArray()
  .then(items => {
    console.log(items);
  })
  .catch(error => {
    console.error(error);
  });

复合索引能让Dexie直接通过索引定位数据,比.and()的过滤方式性能更高,适合频繁执行的多条件查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:52:03