Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update/insert an other document in cloud firestore on receiving a create event for a collection using functions

Let us assume that we have two collections say "users" and "usersList"

Upon creating a new user document in users collection with following object

{username: Suren, age:31}

The function should read the above data and update other collection i.e. "usersList" with the username alone like below

{username: Suren}

Let me know the possibility

The code I have tried is

exports.userCreated = 
functions.firestore.document('users/{userId}').onCreate((event) => {
   const post = event.data.data();

   return event.data.ref.set(post, {merge: true});
})
like image 234
surendher Avatar asked Dec 15 '17 07:12

surendher


People also ask

How do I add files to firestore collection?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

Can firestore update multiple documents matching a condition using one query?

Cloud Firestore does not support the equivalent of SQL's update queries.

What does onSnapshot do?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.


1 Answers

I have done it using below code

exports.userCreated = functions.firestore.document('users/{userId}')
.onCreate((event) => {
    const firestore = admin.firestore()
    return firestore.collection('usersList').doc('yourDocID').update({
        name:'username',
      }).then(() => {
        // Document updated successfully.
        console.log("Doc updated successfully");
      });
})
like image 144
surendher Avatar answered Oct 10 '22 05:10

surendher