Firebase equalto dynamic nested child

ⅰ亾dé卋堺 提交于 2020-01-17 05:34:06

问题


With a structure of

/archive: {
  $userId: {
    $archiveKey: {
      foo: 1
    },
    ...
  },
  ...
}

Where $userId references a user id and $archiveKey is dynamic, created by .push().

Is it possible to query the archive ref and get all archiveObjects where foo = 1 ? Or do I need to fetch down the whole table, manually dig into $userId and extract the archiveObjects I'm looking for?


回答1:


Firebase queries can nowadays query nested paths, but the paths cannot be dynamic.

So if you know the uid, you can query that user's archives with:

ref.child(authData.uid).orderByChild('foo').equalTo(1).on(...

If you don't know the uid, then you'll have to create a data structure that allows you to do the lookup:

archive_category_to_uids: {
  foo: {
    1: {
      uid1: true,
      uid2: true
    }
  }
}

A more common way is to separate the archives into their own top-level list and have both users and categories refer to that:

users: {
  userId1: {
    archiveKey1: true,
    ...
  },
  ...
},
archives: {
  archiveKey1: {
    foo: 1,
    uid: uid1
  },
  ...
},
archiveCategories: {
  foo: {
    1: {
      archiveKey1: true,
      archiveKey2: true
    }
  }
}

Now you can get find the archives with:

ref.child('archiveCategories/foo/1').once('value', function(keys) {
  keys.forEach(function(key) {
    ref.child('archives').child(key.key()).once('value', function(snapshot) {
      console.log(snapshot.val());
    });
  };
});

This process is called denormalization and is quite common in NoSQL databases. You're modeling the data for how your application needs to consume it. For more on this and other common patterns, I recommend reading this article on NoSQL data modeling.



来源:https://stackoverflow.com/questions/36740657/firebase-equalto-dynamic-nested-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!