Firestore的条件where查询

3

我尝试实现了以下解决方案:

Firestore查询中的条件Where子句

Firestore多个条件Where子句

但它们似乎不起作用(请参见下面的代码示例)。 Firestore是否更改了任何内容? 我在下面的代码中弄错了什么吗?

提前感谢!

为了上下文,下面是在React函数组件内useEffect钩子中的代码。 但是,我认为这并不重要,因为没有条件查询的工作示例正常运行。

基本示例 - 硬编码筛选器 - 运行良好。 筛选器已应用

const query = db.collection('todos')
    .where('userId', '==', userId)
    .where('status', '==', 'pending');

query.onSnapshot((res) => {
  const todos = [];
  res.forEach((todo) => {
    todos.push(todo.data());
  });
});
无法正常工作 - 返回具有所有状态的结果。if块内的where查询尚未应用
const query = db.collection('todos').where('userId', '==', userId);

if (filter === 'complete') {
  query.where('status', '==', 'pending');
}
if (filter === 'complete') {
  query.where('status', '==', 'complete');
}
query.onSnapshot((res) => {
  const todos = [];
  res.forEach((todo) => {
    todos.push(todo.data());
  });
});

这是另一个例子,确保 if 代码块本身不是问题所在。创建了一个初始查询,并在 onSnapshot 之前添加了“where”条件。在这种情况下,应用了 userId where 条件,但 status where 条件被忽略了。所有状态为 todo 的都会被返回。

const query = db.collection('todos').where('userId', '==', userId);

query.where( 'status', '==', 'pending' ); // This 'where' clause is being ignored

query.onSnapshot((res) => {
  const todos = [];
  res.forEach((todo) => {
    todos.push(todo.data());
  });
});
1个回答

6
你在引用的问题中没有正确遵循模式。
每次想要添加新条件时,你必须重新分配查询对象。仅仅反复调用where并不能达到你想要的效果。where每次被调用都会返回一个全新的查询对象。你必须继续在该对象上构建,而不是原始的对象。
// use LET, not CONST, so you can ressign it
let query = db.collection('todos').where('userId', '==', userId);

// Reassign query, don't just call where and ignore the return value
if (filter === 'complete') {
  query = query.where('status', '==', 'pending');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接