通过使用云功能,当从“用户”收集的文件进行编辑,编辑后的文件应在uploads
收集无论用户ID存储更新。
对于上述要求我使用下面的函数。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const settings = {
timestampsInSnapshots: true
};
admin.initializeApp();
admin.firestore().settings(settings);
var db = admin.firestore();
exports.updateUser = functions.firestore.document('users/{userId}')
.onUpdate((change, context) => {
var userId = context.params.userId;
const newValue = change.after.data();
const name = newValue.display_name;
var uploadsRef = db.collection('uploads');
uploadsRef.where('user.id', '==', userId).get().then((snapshot) => {
snapshot.docs.forEach(doc => {
doc.set({"display_name" : name}); //Set the new data
});
}).then((err)=> {
console.log(err)
});
});
当此执行,我得到在日志下面的错误。
TypeError: doc.set is not a function
at snapshot.docs.forEach.doc (/user_code/index.js:31:21)
at Array.forEach (native)
at uploadsRef.where.get.then (/user_code/index.js:29:27)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
而且下面。
Unhandled rejection
我该如何处理这个问题?什么是对付快照文件更新的最佳方法?
当您get()对象上做一个Query,它会产生一个QuerySnapshot对象。当你使用它的文档属性,你遍历包含来自匹配的文档中的所有数据QuerySnapshotDocument对象的数组。它看起来像你假设一个QuerySnapshotDocument对象有一个set()方法,但你可以从它没有链接的API文档看。
如果你想要写回的QuerySnapshotDocument标识的文件,使用其ref属性获取DocumentReference对象确实有set()方法。
doc.ref.set({"display_name" : name}); //Set the new data
记住,如果你把这种变化,它将运行,但可能无法更新所有的文件,因为你还忽略了由set()方法返回的承诺。你需要收集所有这些承诺到一个数组中,并使用Promise.all()来生成一个新的承诺,从函数返回。这是必要的,以帮助云功能知道什么时候所有的异步工作就完成了。