I have a cloud function in which I am listening to the onCreate event of a firestore collection. When the cloud function is triggered I am getting a reference error. Below are the cloud function code and the error.
const functions = require('firebase-functions')
const serviceAccount = require('./serviceAccountKey.json')
const admin = require('firebase-admin')
const { firestore } = require('firebase-admin')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://my-app-id.firebaseio.com', // Here I have replaced my real id for privacy
})
const db = admin.firestore()
exports.handleDiscussionReplyAdded = functions.firestore
.document('/discussions/{discussionId}/replies/{replyId}')
.onCreate(async (snap, context) => {
try {
// 1. Creating a ref to parent chat doc
const discussionRef = db
.collection('discussions')
.doc(context.params.discussionId)
// 2. Updating the data
await discussionRef.update({
totalReplies: firestore.FieldValue.increment(1),
})
// Return true if everything went fine
return true
} catch (error) {
// Return error if something went wrong
functions.logger.error(`Error: ${JSON.stringify(error)}`)
return error
}
})
{
"severity": "ERROR",
"message": "ReferenceError: firestore is not defined\n at /Users/syedalirazabokhari/Desktop/Development/React/omanshopping/functions/index.js:23:23\n at cloudFunction (/Users/syedalirazabokhari/Desktop/Development/React/omanshopping/functions/node_modules/firebase-functions/lib/cloud-functions.js:134:23)\n at /usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:590:16\n at runFunction (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:577:15)\n at runBackground (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:589:11)\n at processBackground (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:572:11)\n at invokeTrigger (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:647:19)\n at handleMessage (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:734:15)\n at processTicksAndRejections (internal/process/task_queues.js:93:5)"
}
I tried to debug the issue but unable to resolve. I have also updated the firebase-admin to the latest version 9.5.0 as of now.
const firestore = admin.firestore
? – Frank van Puffelen