构建动态 where 条件 firestore
Build dynamic where condition firestore
默认的查询方式比较复杂。我试图围绕它创建一个包装器,它根据传递给它的字段附加 where 子句。
import { collection, getDocs, getFirestore, query, conditions } from "firebase/firestore";
const db = getFirestore();
export const getDocuments = async ({ collectionName, whereConditions = {}, fetchSingle = false }) => {
const whereQuery = Object.entries((whereConditions)).map(([key, value]) => where(key, "==", value));
const q = query(collection(db, collectionName), ...whereQuery)
const querySnapshot = await getDocs(q);
const result = [];
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
result.push({ id: doc.id, ...doc.data() });
});
return fetchSingle ? result[0] : result;
}
但它在每种情况下都是 returns []
数组。似乎 where()
没有被应用。
更新:
当我登录时 queryWhere
这就是我得到的。
[
{
"hc": {
"segments": [
"id"
],
"offset": 0,
"len": 1
},
"lc": "==",
"fc": "EQdg5wDPFYCEqhImRznD",
"type": "where"
}
]
当我登录时 whereConditions
这是我得到的,
{
"id": "EQdg5wDPFYCEqhImRznD"
}
我尝试了很多组合。当我通过除 id
.
以外的其他过滤器时它正在工作
当 id
传入 where 时,它不会 return 结果。
当前您的查询正在查找文档中的“id”字段。如果您想根据文档 ID 进行查询,请尝试以下操作:
import { documentId } from "firebase/firestore"
const qConstraint = where(documentId(), "==", "DOC_ID")
默认的查询方式比较复杂。我试图围绕它创建一个包装器,它根据传递给它的字段附加 where 子句。
import { collection, getDocs, getFirestore, query, conditions } from "firebase/firestore";
const db = getFirestore();
export const getDocuments = async ({ collectionName, whereConditions = {}, fetchSingle = false }) => {
const whereQuery = Object.entries((whereConditions)).map(([key, value]) => where(key, "==", value));
const q = query(collection(db, collectionName), ...whereQuery)
const querySnapshot = await getDocs(q);
const result = [];
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
result.push({ id: doc.id, ...doc.data() });
});
return fetchSingle ? result[0] : result;
}
但它在每种情况下都是 returns []
数组。似乎 where()
没有被应用。
更新:
当我登录时 queryWhere
这就是我得到的。
[
{
"hc": {
"segments": [
"id"
],
"offset": 0,
"len": 1
},
"lc": "==",
"fc": "EQdg5wDPFYCEqhImRznD",
"type": "where"
}
]
当我登录时 whereConditions
这是我得到的,
{
"id": "EQdg5wDPFYCEqhImRznD"
}
我尝试了很多组合。当我通过除 id
.
当 id
传入 where 时,它不会 return 结果。
当前您的查询正在查找文档中的“id”字段。如果您想根据文档 ID 进行查询,请尝试以下操作:
import { documentId } from "firebase/firestore"
const qConstraint = where(documentId(), "==", "DOC_ID")