I'm using Firebase Cloud Function and since recently, the logs show me this message:
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 = new Firestore(); const settings = {/* your settings... */ timestampsInSnapshots: true}; firestore.settings(settings);
The problem is that when I add that piece of code into my functions file, I get this error every time I try to deploy:
ReferenceError: Firestore is not defined
Can somebody help me find what could be wrong?
(Do I need to add a Firestore dependence in the package.json file? Even if I don't need to do it whereas I already use the Firestore features?)
Thank you
Navigate to the Cloud Firestore section of the Firebase console. You'll be prompted to select an existing Firebase project. Follow the database creation workflow.
You can use both Firebase Realtime Database and Cloud Firestore in your app, and leverage each database solution's benefits to fit your needs.
This should do the work:
const admin = require('firebase-admin');
admin.initializeApp();
const firestore = admin.firestore();
// Add this magical line of code:
firestore.settings({ timestampsInSnapshots: true });
Then in your function use the firestore object directly:
firestore.doc(`/mycollection/${id}`).set({ it: 'works' })
UPDATE as of March, 2019:
If using firebase-admin
version 7.0.0 or above, you no longer need this fix.
In Version 7.0.0 - January 31, 2019 of firebase-admin
there were some breaking changes introduced:
BREAKING: The
timestampsInSnapshots
default has changed to true.The
timestampsInSnapshots
setting is now enabled by default so timestamp fields read from aDocumentSnapshot
will be returned asTimestamp
objects instead ofDate
. Any code expecting to receive aDate
object must be updated.
What's more, as stated in the official docs, timestampsInSnapshots
is going to be removed in a future release so make sure to remove it altogether.
The advice you're getting in the logs is intended for people using the Firestore node SDK directly. However, when you write Firestore triggers through Cloud Functions, the Admin SDK is initialized automatically, which in turn initializes the Firestore SDK automatically. So, you don't have an opportunity to initialize it yourself.
Until the Firestore SDK is fully finalized, all you can do is make sure that your usage of dates is consistent with the future, fully released Firestore SDK. This means you should use Timestamp objects when reading dates out of snapshots. If you're doing that, you can ignore this warning message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With