【问题标题】:Check if item value exists in Firebase array检查 Firebase 数组中是否存在项目值
【发布时间】:2017-02-04 20:17:24
【问题描述】:
{
  "accounts" : {
    "-account1" : {
      "email" : "test@example.com",
      "name" : "John doe",
      "online" : false,
      "profilePic" : "example.com/img.png",
      "username" : "jonh_doe"
      "tokens" : [ 
        "token11111", 
        "token22222",
        "token33333"]
    },
    "-account2" : {
      "email" : "testymctest@example.com",
      "name" : "Jane doe",
      "online" : false,
      "profilePic" : "example.com/img.png",
      "username" : "jane"
      "tokens" : [ 
        "token44444", 
        "token55555",
        "token66666"]
    }
  }
}

我的用户数据结构如上,我正在尝试确定 -account1 是否具有值为“token11111”的令牌

其他 Firebase 示例建议使用快照,但我还没有找到深入到子元素以查找值的示例。

这是我尝试过的

firebase.database().ref('accounts/-account1/tokens')
.equalTo(newToken)
.once('value')
.then(function(tokens) {
        if (tokens.exists()) {
        //Token already exists
        }
        else{
        //Push new token to db  
        }
    });

【问题讨论】:

  • 很难说tokens 真正包含什么。 Firebase 并没有真正的数组结构。在控制台中查看您的数据,您会发现它要么是一个分隔字符串,要么是带有数字键的键/值对,或者令牌是键的键/值对,并且值只是 true .您实际使用的是哪一个?
  • @DougStevenson 他们在键/值对中。抱歉,我的 Firebase 数据库的 Json 导出没有反映这一点
  • 所以它是 '0':'token0'、'1':'token1' 等等?
  • @DougStevenson Yessir

标签: javascript angularjs firebase firebase-realtime-database


【解决方案1】:

当您从 Firebase 快照中获取类似数组的对象(键是从 0 开始的数字)时,您可以像处理常规 JavaScript 数组一样处理它:

var ref = firebase.database().ref('/accounts/-account1/tokens');
ref.once('value').then(function(snap) {
  var array = snap.val();
  for (var i in array) {
    var value = array[i]
    console.log(value);
    if (value == 'whatever') { ... }
  }
});

这将迭代并打印每个值。您可以在该循环中查找您喜欢的任何值。或者您可以在 JavaScript ES2016 中的数组上 includes(x)

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多