【问题标题】:Conditional where query on FirestoreFirestore 上的条件 where 查询
【发布时间】:2020-09-07 13:02:39
【问题描述】:

我已尝试在此处实施解决方案:

Conditional where clause in firestore queries

Firestore: Multiple conditional where clauses

但它们似乎不起作用(参见下面的代码示例)。 Firestore 有什么改变吗?我在下面的代码中搞砸了什么吗?

提前致谢!

对于上下文,下面是一个反应功能组件内的 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 块本身不是问题的例子。创建了一个初始查询,并在其后添加了一个“where”条件(但在 onSnapshot 之前)。在这种情况下,应用了 userId where 子句,但忽略了 status where 子句。返回所有状态的待办事项

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());
  });
});

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    您没有正确遵循 question you cited 中的模式。

    每次要添加新条件时,都必须重新分配查询对象。简单地反复调用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');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2019-04-05
      • 1970-01-01
      • 2023-01-25
      • 2020-11-11
      相关资源
      最近更新 更多