首页 > 解决方案 > Firebase orderByKey().startAt() 未按预期工作。怎么了?

问题描述

我正在尝试从 uid 必须以传递的字符串开头的节点获取 firebase 数据。

我尝试了一个代码,但我总是得到相同的数据。数据库数据如下:

在此处输入图像描述

我正在使用以下代码:

var ref = firebase.database().ref("restaurantes/history");
    ref.orderByKey().startAt(userUID).once("child_added", function(snapshot) {
      snapshot.forEach(child => {
        if(child.key == "orders")
        {
          console.log(child.val());

          _.each(child.val(), (value, key) => {
            arrtmp.push(value)
          })
        }    

      })

如果用户是“FKQLlqa”,我应该得到图片中显示的历史数据。如果我的用户是“abc”,我不应该得到任何数据。但我总是得到图片中显示的数据。我应该使用另一种查询方式吗?或者我应该在订单和付款数据中使用一个关键字段?

问候!

标签: javascriptfirebasefirebase-realtime-database

解决方案


尝试以下操作:

var ref = firebase.database().ref("restaurantes/history");
ref.child(userUID).once("value", function(snapshot) {
  if (snapshot.exists()) {
      console.log(snapshot.val());
    }
  else {
      console.log("different user");    
  });

这将检查包含userId(作为child()方法中的参数添加)的快照是否已存在于数据库中,然后您将能够检索userId.

以供参考:

https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists


推荐阅读