Juste Guipi
Juste Guipi

Reputation: 67

Write data to document on creation

I'm new to Firebase cloud function and I'm trying to write data down in a document every time a document is created, but the data is never written and I get no error in the console. Did I miss something? I'm using firestore.

exports.updateclient = functions.firestore
  .document('patients/{clientId}')
  .onCreate(async (snap, context) => {
    const database = admin.firestore();
    const settings = {timestampsInSnapshots: true};
    database.settings(settings);
    const clientId= context.params.clientId;
    const patientRef = database.collection('patient').doc(clientId);
    return patientRef.set({ id: clientId}, {merge: true});
  });

Upvotes: 0

Views: 52

Answers (2)

Carlo Field
Carlo Field

Reputation: 724

As Doug already mentioned, you try to update your patients document in a different collection. If this is indeed the error, consider updating it by using

snap.ref.update({
    id: clientId
});

instead. This will use the existing reference you have from the snapshot you got on the function trigger and it will also use update instead of a merge set, which is more syntactically correct. It will also help prevent errors like the potential one above.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317760

You're triggering on documents in a collection called "patients":

exports.updateclient = functions.firestore
  .document('patients/{clientId}')

But you're writing back to a document in a different collection called "patient":

const patientRef = database.collection('patient').doc(clientId);

Did you mean to write back to the "patients" collection instead of "patient"?

Upvotes: 1

Related Questions