Justin Spring
Justin Spring

Reputation: 37

How to update a collection using cloud function?

I would like to update the score using a cloud function

I've tried this so far

exports.rate = functions.https.onRequest((request, response) => {
  admin
.firestore()
.collection()
.where("index", "==", request.index)
.get()
.then(snap => {
  snap.forEach(x => {
    const newRating = x.data().score + request.value;
    firebase
      .firestore()
      .collection()
      .doc(x.id)
      .update({ score: newRating });
  });
});
});

Upvotes: 2

Views: 2037

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

The following should work:

exports.rate = functions.https.onRequest((request, response) => {
    admin
        .firestore()
        .collection('someName') //IMPORTANT! You need to identify the collection that you want to query
        .where('index', '==', request.index)
        .get()
        .then(snap => {
            let batch = admin.firestore().batch();
            snap.forEach(x => {
                const newRating = x.data().score + request.value;
                const ratingRef = admin  //here use admin.firestore() and not firebase.firestore() since in a Cloud Function you work with the Admin SDK
                    .firestore()
                    .collection('someOtherName')  //You need to identify the collection
                    .doc(x.id);
                batch.update(ratingRef, { score: newRating });
            });
            // Commit and return the batch
            return batch.commit();
        })
        .then(() => {
            response.send({result: 'success'});
        })
        .catch(error => {
            response.status(500).send(error);
        });
});
  1. You need to identify the collections you either want to query or in which you want to update a document, see https://firebase.google.com/docs/firestore/query-data/queries and https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#collection. In other words, you cannot do

    admin.firestore().collection().where(...)

without passing a value to collection()

  1. You need to send a response at the end, see this video from the official Video Series: https://www.youtube.com/watch?v=7IkUgCLr5oA

  2. Finally, you should use a batched write, since you want to update several documents in parallel, see https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes and https://firebase.google.com/docs/reference/js/firebase.firestore.WriteBatch

Upvotes: 3

Related Questions