如何使用VueJS从Firebase检索集合的子项

时间:2019-02-25 21:41:45

标签: javascript firebase firebase-realtime-database vuejs2

我无法从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。

有人可以帮助我吗?我已经为此动了好几个小时。

2 个答案:

答案 0 :(得分:1)

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

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

更可能的方法:

once()

我强烈建议您在继续学习Firebase之前,先搜索一个简单的简短教程。花一个小时在此基础上构建类似聊天应用的事情,可能会在几秒钟内向您显示方法的错误。


请注意,您似乎也误解了排序和过滤的工作方式。您所执行的查询告诉数据库以雇员的所有子节点的名字对它们进行排序,然后找到以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()); }); }) 开头的第一个子节点,并在此之后返回所有子节点。其中还包括以JKL等开头的子节点。如果您不希望这样做,则可以告诉Firebase在某个时候停止返回节点:

M

这里const query = rootRef.child('employees').orderByChild('name').startAt('J').endAt('J\uF8FF') 是最后一个可打印的unicode字符,可确保您获得以uF8FF开头的所有结果(但仅限于那些结果)。


答案 1 :(得分:0)

看一下文档,看来这不是orderByChildstartAt的预期用途

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

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

另一种(未经检验的)可能性是...

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