Firebase云函数报错:get.then不是函数,求助实现评论通知功能
Fixing the
TypeError: admin.firestore(...).collection(...).doc(...).collection(...).doc(...).get.then is not a function Error Hey there! Let's break down what's causing this error and fix it right away.
The Root Cause
That error pops up because you're missing parentheses after the get method. In Firestore, get() is an asynchronous function that returns a Promise—you need to call it (with parentheses) before you can chain .then() to handle the result. Without the parentheses, you're trying to access a then property on the function itself, which doesn't exist.
Corrected Code Example
Here's how to fix your sendNotification function, with the missing parentheses added and a complete implementation to send the notification:
'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sendNotification = functions.firestore .document('Users/{userID}/Notifications/{notificationID}') .onCreate(async (snapshot, context) => { // Get the notification data from the new document const notificationData = snapshot.data(); const userID = context.params.userID; try { // Fetch the user's device token - notice the parentheses after get() const userDoc = await admin.firestore() .collection('users') .doc(userID) .get(); // <-- This is where you were missing parentheses if (!userDoc.exists) { console.log(`User ${userID} not found`); return; } const userData = userDoc.data(); const deviceToken = userData.deviceNotificationToken; if (!deviceToken) { console.log(`User ${userID} has no device token`); return; } // Prepare the notification payload const payload = { notification: { title: 'New Comment', body: notificationData.commentText || 'You received a new comment', sound: 'default' } }; // Send the notification await admin.messaging().sendToDevice(deviceToken, payload); console.log('Notification sent successfully'); } catch (error) { console.error('Error sending notification:', error); } });
Key Notes
- Always use parentheses when calling Firestore asynchronous methods like
get(),set(),update(), etc.—these are functions, not properties. - If you prefer using
.then()chains instead ofasync/await, you can adjust that part like this:admin.firestore() .collection('users') .doc(userID) .get() // <-- Parentheses here! .then(userDoc => { // Handle the user document data }) .catch(error => { // Handle errors });
内容的提问来源于stack exchange,提问作者Mahmoud Eidarous
相关产品推荐
相关产品推荐

