【问题标题】:firestore query multiple filter to retrieve collection in react-native [duplicate]firestore查询多个过滤器以检索react-native中的集合[重复]
【发布时间】:2020-11-30 01:37:29
【问题描述】:

Firestore 查询条件 查询结果的console.log 源代码-渲染数据 我是反应原生 Firebase Firestore 的新手。 我正在设计一个应用程序,其功能是用户应该能够在三个条件中的任何一个上搜索注册用户:

  1. 按名称

  2. 专业知识

  3. 按位置

如果用户在这些字段中明确键入,我的代码将从 firestore 检索过滤结果

反应原生代码从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){/* ... */}

场景: 如果用户没有在 UI 中为任何一个字段输入任何搜索条件,比如“位置”,那么在这种情况下,我不想从 firestore 为该条件设置过滤器。 这意味着,预期的代码应该是:

   var queryResult = routeRef
    .where(("Name", "==", NameInput)
    .where("Expertise", "==", ExpertiseInput)

问题: 我不确定如何根据用户是否输入 UI 来动态设置 .where 条件。 有人可以帮忙吗?

这还是没有得到查询结果

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    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);
    })
    

    【讨论】:

    • 非常感谢。让我试着尽快更新你
    • Jay Codist 谢谢
    • Jay Codist,我试过但没有得到结果。我不确定这是什么原因。请参阅随附的 VSS 代码屏幕截图。感谢您的帮助
    • 哦,我明白你做错了什么。更新我的答案@Bhol。基本上,将您的 snapshot.forEach() 更改为 snapshot.docs.forEach()
    • -非常感谢。现在工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多