i'm trying to convert my firebase cloud functions from 1st Gen to 2nd Gen and i can't get the data out of the snapshot
typically referred to as event
. There must be a simple fix that i'm missing.
In 1st Gen functions, i used to be able to use snapshot.data()
, snapshot.data().email
and snapshot.data().userName
to get the new document's data. But snapshot.data() in 2nd Gen produces a TypeError:
functions: TypeError: Cannot read properties of undefined (reading 'data')
Here is the code where i'm just trying to tap into the fields when user signs up and a new profile is created.
exports.profileCreation = onDocumentCreated(
"profiles/{profile}",
async (snapshot) => {
const { data } = snapshot;
console.log("Data: ", data);
console.log("Snapshot: ", snapshot);
);
console.log("Snapshot Data: ", snapshot.data());
}
);
Below is the screenshot of the snapshot data that i get and the square highlights the section in the data that i'm looking for:
Snapshot: {
> specversion: '1.0',
> type: 'google.cloud.firestore.document.v1.created',
> source: '//firestore.googleapis.com/projects/projects/demo-project/databases/(default)',
> id: '2f47ffda-ce71-4aa7-9ad9-626a7fb84c99',
> subject: 'documents/profiles/Yp9sj71F0cABnr8dRADHapePqJHY',
> time: '2025-04-12T07:52:09Z',
> location: 'us-central1',
> project: 'demo-project',
> database: '(default)',
> namespace: '(default)',
> document: 'profiles/Yp9sj71F0cABnr8dRADHapePqJHY',
> data: QueryDocumentSnapshot {
> _fieldsProto: {
> userName: [Value], //information i'm looking for
> adminPublish: [Value], //information i'm looking for
> email: [Value], //information i'm looking for
> initiatedAt: [Value] //information i'm looking for
> },
> _ref: DocumentReference {
> _firestore: [Firestore],
> _path: [QualifiedResourcePath],
> _converter: [Object]
> },
> _serializer: Serializer {
> createReference: [Function (anonymous)],
> createInteger: [Function (anonymous)],
> allowUndefined: false
> },
> _readTime: undefined,
> _createTime: Timestamp { _seconds: 1744444329, _nanoseconds: 641001000 },
> _updateTime: Timestamp { _seconds: 1744444329, _nanoseconds: 641001000 }
> },
> params: { profile: 'Yp9sj71F0cABnr8dRADHapePqJHY' }
> }
How do i easily get access to new document data? What am I missing?
The API changed entirely between gen1 and gen2. The first argument to your handler function is no longer a DocumentSnapshot object. It's now a FirestoreEvent object. See the example in the documentation:
exports.createuser = onDocumentCreated("users/{userId}", (event) => {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const snapshot = event.data;
if (!snapshot) {
console.log("No data associated with the event");
return;
}
const data = snapshot.data();
The DocumentSnapshot you're looking for is in the data
property of event
.