Bho*_*hol 4 javascript firebase react-native google-cloud-firestore
Firestore 查询条件
查询结果的console.log
源代码-渲染数据
我是新来反应本机 firebase firestore 的。我正在设计一个应用程序,其功能是用户应该能够根据三个标准中的任何一个搜索注册用户:
按名字
按专业知识
按地点
如果用户明确输入这些字段,我的代码将从 firestore 检索过滤结果
React Native 中从 firestore 检索的代码:
var db = firebase.firestore();
var routeRef = db.collection("users");
var queryResult = routeRef
.where(("Name", "==", NameInput)
.where("Expertise", "==", ExpertiseInput)
.where("Location","==" , LocationInput))
.get().then(function(snapshot){/* ... */}
Run Code Online (Sandbox Code Playgroud)
场景:如果用户没有在 UI 中的任何一个字段中输入任何搜索条件(例如“位置”),在这种情况下,我不想从 firestore 设置该条件的过滤器。这意味着,预期的代码应该是:
var queryResult = routeRef
.where(("Name", "==", NameInput)
.where("Expertise", "==", ExpertiseInput)
Run Code Online (Sandbox Code Playgroud)
问题:我不确定如何根据用户是否在 UI 中输入来动态设置 .where 条件。有人可以帮忙吗?
还是这样没有得到查询结果
该where()函数返回一个对象(它允许您首先Query查询多个条件)。where()因此,您可以有条件地“保存逐步进度”。像这样的东西:
const routeRef = db.collection("users");
const nameFilter = NameInput ? routeRef.where("Name", "==", NameInput) : routeRef;
const expertiseFilter = ExpertiseInput ? nameFilter.where("Expertise", "==", ExpertiseInput) : nameFilter;
const locationFilter = LocationInput ? expertiseFilter.where("Location", "==", LocationInput) : expertiseFilter;
locationFilter.get().then(snapshot => {
// The snapshot returned by `where().get()` does not have a `data()` reference since it returns multiple documents, it has `docs` property which is an array of all the documents matched
snapshot.docs.forEach(doc => {
const docData = { ...doc.data(), id: doc.id };
console.log(docData);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6189 次 |
| 最近记录: |