Firestore 上的条件 where 查询

Hem*_*mal 3 javascript firebase google-cloud-firestore

我试过在这里实施解决方案:

Firestore 查询中的条件 where 子句

Firestore:多个条件 where 子句

但它们似乎不起作用(请参阅下面的代码示例)。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());
  });
});
Run Code Online (Sandbox Code Playgroud)

不起作用 - 返回具有所有状态的结果。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());
  });
});
Run Code Online (Sandbox Code Playgroud)

另一个确保 if 块本身不是这里的问题的示例。创建了一个初始查询并在它之后(但在 onSnapshot 之前)添加了一个“where”条件。在这种情况下,会应用 userId where 子句,但忽略状态 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());
  });
});
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 5

您没有正确遵循您引用问题中的模式。

每次要添加新条件时,都必须重新分配查询对象。简单地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');
}
Run Code Online (Sandbox Code Playgroud)