云修复-云函数:TypeError: collectionRef.child不是一个函数
我正在使用Cloud函数来更新Cloud的父集合中的注释号,所以当注释添加时,云函数可以自动更新注释号。
云修复-云函数:TypeError: collectionRef.child不是对象上的函数(/user_code/index.js:23:33)。(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (原生) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:716:24 at process._tickDomainCallback (内部/process/next_tick.js:135:7)
守则是:
exports.updateCommentNumbers1 = functions.firestore
.document('postlist/{postlistId}/comments/{commentsID}')
.onCreate((change, context) =>
{
const collectionRef = change.ref.parent;
const countRef = collectionRef.child('comment_number');
let increment;
if (change.after.exists() )
{
increment = 1;
}
else
{
return null;
}
return countRef.transaction((current) =>
{
return (current || 0) + increment;
}).then(() =>
{
return console.log('Comments numbers updated.');
});
});问题是
谢谢。
发布于 2018-05-14 02:32:13
代码中的collectionRef是一个CollectionReference类型的对象。从API文档中可以看到,该对象上没有子()方法。实际上,集合根本没有任何可分配的属性。您只能将信息存储在文档中,并且文档必须存在于某些集合中。
因此,您必须找出要存储此计数值的文档(哪个集合),并修改文档中的某个字段。
另外,传递给onCreate的匿名函数的第一个参数不是"change“对象。这是一个DocumentSnapshot。onUpdate和onWrite接收“更改”对象,这是另一回事。
发布于 2018-05-14 17:49:26
最后,我花了两天多的时间才弄明白:
第一个问题的答案是change.after.ref.parent;
云修复的云函数示例非常少。
所有的例子都是火基实时数据库。
exports.updateCommentNum = functions.firestore
.document('post/{postId}/comments/{commentsID}')
.onWrite((change, context) =>
{
const db = admin.firestore();
const collectionRef = change.after.ref.parent;//'post/{postId}/comments/'
const countRef = collectionRef.parent;//'post/{postId}/'
return db.runTransaction(t =>
{
return t.get(countRef).then(restDoc =>
{
var newNumber;
newNumber = restDoc.data().comment_number + 1;
newNumber = newNumber || 1;//filter any "falsey" value to 1.
//The "falsey" values are:false/null/undefined/0/"" ( empty string )/NaN ( Not a Number )
return t.set(countRef, {comment_number: newNumber}, {merge: true});
});
});
});https://stackoverflow.com/questions/50322373
复制相似问题