我想使用云功能更新分数
到目前为止,我已经尝试过了
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 });
});
});
});
答案 0 :(得分:1)
以下方法应该起作用:
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);
});
});
您需要标识要查询的集合或要在其中更新文档的集合,请参见https://firebase.google.com/docs/firestore/query-data/queries和https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#collection。换句话说,您不能
admin.firestore()。collection()。where(...)
不将值传递给collection()
您需要在最后发送回复,请参见官方视频系列中的以下视频:https://www.youtube.com/watch?v=7IkUgCLr5oA
最后,您应该使用批量写入,因为您要并行更新多个文档,请参见https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes和https://firebase.google.com/docs/reference/js/firebase.firestore.WriteBatch