如何where()使用 Firebase Modular SDK (v9) 执行带有条件子句的查询?
名称空间版本 (v8) 中的示例查询:
const status = "live"
const publishedAfter = 1630607348811
let q = firebase.firestore().collection("articles")
// filters selected by users
if (status) q = q.where("status", "==", "live")
if (publishedAfter) q = q.where("publishedAt", ">", publishedAfter)
const qSnapshot = await q.get()
Run Code Online (Sandbox Code Playgroud) 我试过在这里实施解决方案:
但它们似乎不起作用(请参阅下面的代码示例)。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) …Run Code Online (Sandbox Code Playgroud) 我的代码有问题,我不知道如何以正确的方式解决它。
我正在尝试编写一个过滤器,当用户单击每个过滤器时,它会自动从 Firestore 查询数据。
在我的 Redux Saga 中有这个:
const {type, currency, location} = action.payload;
Run Code Online (Sandbox Code Playgroud)
一切正常,但问题是当我尝试使用动态输入查询数据时:例如:
firebase
.firestore()
.collection("ItemData")
.where("type", "==", type)
.where('currency', '==', currency)
.where('location', '==', location)
Run Code Online (Sandbox Code Playgroud)
当用户单击选项时,type它不显示任何输入currency并且location没有数据,只有空字符串,因此查询返回无响应。除非您单击所有过滤器,否则它将显示正确的响应。
那么我该如何解决这个问题呢?