我尝试在这里实施解决方案:
firestore 查询中的条件 where 子句 https://stackoverflow.com/questions/48514932/conditional-where-clause-in-firestore-queries
Firestore:多个条件 where 子句 https://stackoverflow.com/questions/48036975/firestore-multiple-conditional-where-clauses
但它们似乎不起作用(请参阅下面的代码示例)。 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 块本身不是问题的示例。创建了一个初始查询,并在其后添加了一个“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());
});
});