Home > Back-end >  firebase cloud functions iterate over collection
firebase cloud functions iterate over collection

Time:01-04

I am building a forum, and when a person comments on a thread, I would like to email everyone that someone has added a comment. This requires iterating over a firestore collection. How do I do this using firebase cloud functions?

exports.onCommentCreation = functions.firestore.document('/forum/threads/threads/{threadId}/comments/{commentId}')
 .onCreate(async(snapshot, context) => {

     var commentDataSnap = snapshot; 

     var threadId = context.params.threadId; 
     var commentId = context.params.commentId; 

     // call to admin.firestore().collection does not exist
     var comments = await admin.firestore().collection('/forum/threads/threads/{threadId}/comments/');

     // iterate over collection
 });

CodePudding user response:

You need to run get query, not sure what is admin here, but you can do like this:

const citiesRef = db.collection('cities'); // pass your collection name
const snapshot = await citiesRef.where('capital', '==', true).get(); // query collection
if (snapshot.empty) {
  console.log('No matching documents.');
  return;
}  

snapshot.forEach(doc => {
  console.log(doc.id, '=>', doc.data());
});

You can check this link, for more details.

Also, I would suggest you go through this link to correctly set up the cloud function for firestore if there are any issues with it.

  • Related