Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functionscloud

Firestore cloud functions : cannot read property 'userId' of undefined


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)

Solution

  • 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)
    }