javascript - Firestore 上的条件 where 查询

标签 javascript firebase google-cloud-firestore

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

Conditional where clause in firestore queries

Firestore: Multiple conditional where clauses

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

提前致谢!

对于上下文,下面是在 react 功能组件内的 useEffect Hook 中。但是,我认为这无关紧要,因为下面的工作示例(没有条件查询)工作正常。

基本示例 - 过滤器硬编码 - 工作正常。过滤器已应用

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

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

不起作用 - 返回具有所有状态的结果。 IF block 中的 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 block 本身不是问题的示例。创建了一个初始查询,并在它之后(但在 onSnapshot 之前)添加了一个“where”条件。在这种情况下,应用了 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());
  });
});

最佳答案

您没有正确遵循 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');
}

关于javascript - Firestore 上的条件 where 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61925363/

相关文章:

javascript - 道场表单/按钮改变颜色

javascript - 如何正确检查是否所有表单元素都填充了 JavaScript

javascript - 使用 react-router 处理 firebase 身份验证

android - 无需控制台即可在客户端访问 firebase/google 分析数据

angular - 如何查询包含一个字段值的对象数组firebase angular?

firebase - 函数的返回类型为 'Future<String>' 但不以 return 语句结尾

javascript - 在屏幕中间叠加位置和淡入淡出

javascript - 仅基于 CSS 的水平多级菜单

android - 从子节点跳转到 Firebase 父节点

javascript - 扩展中的 Firestore API key