【问题标题】:How to retrieve childs of a collection from Firebase with VueJS如何使用 VueJS 从 Firebase 检索集合的子项
【发布时间】:2019-07-19 09:10:08
【问题描述】:

我无法从 firebase 获取正确的结果。

我的代码是

const rootRef = firebase.database().ref()
console.log(rootRef)
const allEmployees = rootRef.child('employees').orderByChild('name').startAt('J')
console.log("These are all employees which names start with a J" + allEmployees)

这是控制台中的结果

Reference {repo: Repo, path: Path, queryParams_: QueryParams, 
 orderByCalled_: false}
 database: (...)
 key: (...)
 orderByCalled_: false 
 parent: (...)
 path: Path {pieces_: Array(0), pieceNum_: 0}
 queryParams_: QueryParams {limitSet_: false, startSet_: false, 
 startNameSet_: false, endSet_: false, endNameSet_: false, …}
 ref: (...)
 repo: Repo {repoInfo_: RepoInfo, app: FirebaseAppImpl, dataUpdateCount: 
 0, statsListener_: null, eventQueue_: EventQueue, …}
 root: (...)
 __proto__: Query

These are all employees which names start with a J https://xxxxxxxx .firebaseio.com/employees

我试图实现的是打印出符合条件的员工列表,即他们的名字以 J 开头。

我还尝试匹配员工所属的类别

rootRef.child('employees').orderByChild('categoryID').equalTo('608Av3zkDS0cg2Iu66b2')
console.log(allEmployees)

但这给出了相同的结果,即数据库的 url。

谁能帮帮我。我已经为此烦恼了好几个小时。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database vuejs2


    【解决方案1】:

    您当前的代码所做的只是创建对 Firebase 实时数据库的查询。它尚未执行该查询,因此没有结果可显示。您最终打印的只是查询对象的定义。

    要从数据库中获取结果,请使用on()once() 将侦听器附加到查询,如documentation on listeners 所示。

    更可能的方法:

    const rootRef = firebase.database().ref()
    const query = rootRef.child('employees').orderByChild('name').startAt('J')
    query.once('value', function(snapshot) {
      snapshot.forEach(function(employeeSnapshot) {
        console.log(employeeSnapshot.key, employeeSnapshot.val());
      });
    })
    

    我强烈建议在继续之前搜索有关 Firebase 的简单简短教程。花了一个小时来构建类似聊天应用程序的东西,可能会在几秒钟内向您展示您的方法的错误。


    请注意,您似乎也误解了排序和过滤的工作原理。您的查询告诉数据库按名字对所有员工子节点进行排序,然后找到以J 开头的第一个子节点,然后返回所有子节点。这还包括以KLM 等开头的子节点。如果您不希望这样,您需要告诉 Firebase 在某个时候停止返回节点:

    const query = rootRef.child('employees').orderByChild('name').startAt('J').endAt('J\uF8FF')
    

    uF8FF 是最后一个可打印的 unicode 字符,可确保您获得以 J 开头的所有结果(但仅限于那些结果)。


    【讨论】:

    • 感谢您回答弗兰克。我会这样做的。
    【解决方案2】:

    查看文档,这似乎不是 orderByChildstartAt 的预期用途

    startAt 似乎用于分页,因此它希望字符串值与找到的第一个节点匹配。

    查看问题Firestore query documents startsWith a string 以了解实现starts with 功能的选项。我不会复制/粘贴他们的答案。

    另一种(未经测试的)可能性是......

    如果您经常执行此查询,您可以在每个节点上创建一个属性(称为startsWith)。这将保存name 属性的大写首字母,然后您可以执行该功能。 orderByChild('startsWith') 可能不会对startsWith 中的名称进行排序,除非您在之后对其应用另一种排序。

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2021-03-24
      • 2018-12-13
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2019-05-28
      • 2018-07-26
      相关资源
      最近更新 更多