【发布时间】:2018-12-31 15:08:56
【问题描述】:
已经看到在 react-native 应用程序中初始化 firestore 的两种不同方法,并且想知道两者之间的区别是什么。 firestore 文档中显示的方法 (https://firebase.google.com/docs/firestore/quickstart#initialize) 看起来像
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
export fs = admin.firestore();
而“firebase”方式(如在本博文中看到的:https://forums.expo.io/t/open-when-an-expo-firebase-firestore-platform/4126/29),这是我目前使用并且似乎可以工作的方式,看起来像
import * as firebase from 'firebase';
import 'firebase/firestore';//for using firestore functions, see https://stackoverflow.com/a/50684682/8236733
import { firebaseConfig } from './firebase-credentials';//WARN: gitignored, exports object containing firebase (web)app credentials
// Initialize Firebase
// why in separate file? see https://github.com/zeit/next.js/issues/1999 and https://ilikekillnerds.com/2018/02/solving-issue-firebase-app-named-default-already-exists/
// firebase.initializeApp(firebaseConfig);
try {
firebase.initializeApp(firebaseConfig)
/*WARN:
@firebase/firestore:, Firestore (5.0.4):
The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the
following code to your app before calling any other Cloud Firestore methods:
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
With this change, timestamps stored in Cloud Firestore will be read back as
Firebase Timestamp objects instead of as system Date objects. So you will also
need to update code expecting a Date to instead expect a Timestamp. For example:
// Old:
const date = snapshot.get('created_at');
// New:
const timestamp = snapshot.get('created_at');
const date = timestamp.toDate();
Please audit all existing usages of Date when you enable the new behavior. In a
future release, the behavior will change to the new behavior, so if you do not
follow these steps, YOUR APP MAY BREAK.
*/
const fsSettings = {/* your settings... */ timestampsInSnapshots: true};
firebase.firestore().settings(fsSettings)
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
export const fs = firebase.firestore()
链接到的帖子是我能找到其他人这样做的唯一实例,但它再次对我有用(可以读取和写入到 Firestore)。
对使用 firebase/firestore 非常陌生,希望使用更“正确”的方法。以这些不同的方式在应用程序中初始化 firestore 有什么区别吗?
【问题讨论】:
标签: react-native google-cloud-firestore