如何使用云功能更新收藏集? [英] How to update a collection using cloud function?

查看:64
本文介绍了如何使用云功能更新收藏集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用云功能更新分数

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

推荐答案

以下方法应该起作用:

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. 您需要标识要查询的集合或要在其中更新文档的集合,请参见

  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(...)

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

不将值传递给collection()

  1. 您需要在最后发送回复,请参阅官方视频系列中的以下视频:最后,您应该使用批量写入,因为您希望并行更新多个文档,请参见

    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

    这篇关于如何使用云功能更新收藏集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆