0
votes

I promise i thoroughly checked through all the previous asked questions and there isn't anything similar to this. I have a firebase function that listens to onCreate on a firestore collection.

exports.sendEmail = functions.firestore.document('/Users/{documentId}')
    .onCreate((snap, context) => {

        const username = snap.data().username;
        const email = snap.data().email;

        console.log(username, email)

        const mailRef = functions.firestore.document('/mail')
        return mailRef.ref.set({
            email: email,
            subject: 'Welcome'

        });


    });

After a document is created in Users, i want to take the data in users and create a new document in a main collection called mail. Is this possible because i've read the docs like 10 times and there's nothing on this. Any help is highly appreciated.

1
TypeError: Cannot read property 'set' of undefined - abdi
when i remove 'ref' i get TypeError: mailRef.set is not a function - abdi
You'll have to figure out exactly which document you want to write to. /mail is not a full document path. "mail" might be a collection, but you'll need a document ID to write to as well. Or maybe accept a random document ID. What specifically are you expecting to happen? - Doug Stevenson
I'm trying to create a document with a random id with those fields - abdi

1 Answers

1
votes

To create a document in cloud functions, then you need to use the admin sdk, so first install the package:

npm install firebase-admin --save

initialize the admin sdk:

const admin = require('firebase-admin');

admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

const db = admin.firestore();

Then you can add:

       const mailRef = db.collection('mail')
        return mailRef.add({
            email: email,
            subject: 'Welcome'

        });

https://googleapis.dev/nodejs/firestore/latest/CollectionReference.html#add