以编程方式更改默认的 firebase 数据库,并且 运行 相同的 firebase 在默认数据库和辅助数据库上运行

Change default firebase database programmatically and run the same firebase functions both on default and secondary database

背景 - 我正在设置一项新功能,允许用户 select 他们所在的城市,因为我的应用程序是 public 交通应用程序。我希望城市位于单独的数据库中,为此我在我的 firebase 项目中创建了一个辅助数据库。这是一个 React Native 应用程序,我正在使用 react-native-firebase。

问题 1 - 当用户 select 位于不同的城市时,我希望该数据库成为他的默认数据库。我不知道该怎么做,有人可以帮忙吗?

我已经尝试初始化并仅更改数据库 URL,即使我连接到第二个数据库一次,但并不是每次都这样做。似乎是一个不稳定的解决方案。

我发现的另一个解决方案是将 url 传递给每个 "firebase.database(url)",但这似乎是一个糟糕的解决方案。

问题 2 - 由于这两个城市的应用程序完全相同,我想 运行 我已经在 DB1 和 DB2 上 运行 的相同功能。它们是完全独立的数据库,但具有完全相同的节点。例如,两者都有一个 "location" 节点,然后我有一个侦听器用于那里的更改。如何仅使用一种功能在两个数据库上设置侦听器?或者我是否需要获得对 DB2 的引用并复制函数?

每个用户没有默认数据库的概念。这意味着您需要从 JavaScript 代码初始化 Firebase,如 React Native Firebase 文档中所示:

// pluck values from your `GoogleService-Info.plist` you created on the firebase console
const iosConfig = {
  clientId: 'x',
  appId: 'x',
  apiKey: 'x',
  databaseURL: 'x',
  storageBucket: 'x',
  messagingSenderId: 'x',
  projectId: 'x',

  // enable persistence by adding the below flag
  persistence: true,
};

// pluck values from your `google-services.json` file you created on the firebase console
const androidConfig = {
  clientId: 'x',
  appId: 'x',
  apiKey: 'x',
  databaseURL: 'x',
  storageBucket: 'x',
  messagingSenderId: 'x',
  projectId: 'x',

  // enable persistence by adding the below flag
  persistence: true,
};

const kittensApp = firebase.initializeApp(
  // use platform specific firebase config
  Platform.OS === 'ios' ? iosConfig : androidConfig,
  // name of this app
  'kittens',
);

// dynamically created apps aren't available immediately due to the
// asynchronous nature of react native bridging, therefore you must
// wait for an `onReady` state before calling any modules/methods
// otherwise you will most likely run into `app not initialized` exceptions
kittensApp.onReady().then((app) => {
   // --- ready ---
   // use `app` arg, kittensApp var or `app('kittens')` to access modules
   // and their methods. e.g:
   firebase.app('kittens').auth().signInAnonymously().then((user) => {
       console.log('kittensApp user ->', user.toJSON());
   });
});