Как обновить коллекцию с помощью облачной функции? - PullRequest
0 голосов
/ 07 января 2019

Я хотел бы обновить счет, используя облачную функцию

Я уже пробовал это

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 });
  });
});
});

1 Ответ

0 голосов
/ 07 января 2019

Должно работать следующее:

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. Вам необходимо указать коллекции, которые вы хотите запросить или в которых хотите обновить документ, см. https://firebase.google.com/docs/firestore/query-data/queries и https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#collection. Другими словами, вы не можете сделать

    admin.firestore (). Collection (). Где (...)

без передачи значения collection()

  1. Вам необходимо отправить ответ в конце, посмотрите это видео из официальной серии видео: https://www.youtube.com/watch?v=7IkUgCLr5oA

  2. Наконец, вы должны использовать пакетную запись, поскольку вы хотите обновить несколько документов параллельно, см. https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes и https://firebase.google.com/docs/reference/js/firebase.firestore.WriteBatch

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...