Reputation: 147
I am not able to send the welcome email from cloud functions. Whenever a new user is created in my firestore withing "Users" collection with the path Users/userId.Here is my function
exports.welcomeEmail = functions.firestore.document('Users/{userId}')
.onCreate((snap, context)=>{
const userId = context.params.userId;
const db = admin.firestore()
return db.collection('Users').doc(userId)
.get()
.then(doc => {
const user = doc.data()
const msg = {
to: user.email,
from: '[email protected]',
subject: 'Welcome to COFOZ',
templateId: '1c455865-4529-4ae1-8e5a-9a5b8eaf0157',
substitutionsWrappers: ['{{', '}}'],
substitutions: {
name: user.name
}
};
return sgMail.send(msg)
})
.then(() => console.log('email sent!'))
.catch(err => console.log(err))
})
This is the error that I am getting.
TypeError: Cannot read property 'userId' of undefined
at exports.welcomeEmail.functions.firestore.document.onCreate.event (/user_code/index.js:19:32)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:710:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Upvotes: 2
Views: 4518
Reputation: 596
No need to get the new user by looking by userid in documents. Just get the newly created document from snap.
exports.welcomeEmail = functions.firestore.document('Users/{userId}')
.onCreate((snap, context)=>{
const user = snap.data();
const msg = {
to: user.email,
from: '[email protected]',
subject: 'Welcome to COFOZ',
templateId: '1c455865-4529-4ae1-8e5a-9a5b8eaf0157',
substitutionsWrappers: ['{{', '}}'],
substitutions: {
name: user.name
}
return sgMail.send(msg)
}
Upvotes: 2
Reputation: 83068
You are probably using an old version of the Cloud Functions SDK. Can you check the version you are using in the package.json
file, under the "dependencies" node?
With the syntax you are using in your code, you should have a version which is equal or above 1.0.0.
See this doc (Migration Guide) for more info: https://firebase.google.com/docs/functions/beta-v1-diff and check the version in your package.json file.
You will see that to update to the new SDK, you should do:
npm install firebase-functions@latest --save
npm install [email protected] --save
Upvotes: 1