首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >云修复-云函数:TypeError: collectionRef.child不是一个函数

云修复-云函数:TypeError: collectionRef.child不是一个函数
EN

Stack Overflow用户
提问于 2018-05-14 02:22:35
回答 2查看 1.5K关注 0票数 3

云修复-云函数: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)

守则是:

代码语言:javascript
复制
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.');
    });
});

问题是

  1. 如何通过父集合的子集合引用父集合?
  2. 如何获得父集合的字段值并更新它?

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2018-05-14 02:32:13

代码中的collectionRef是一个CollectionReference类型的对象。从API文档中可以看到,该对象上没有子()方法。实际上,集合根本没有任何可分配的属性。您只能将信息存储在文档中,并且文档必须存在于某些集合中。

因此,您必须找出要存储此计数值的文档(哪个集合),并修改文档中的某个字段。

另外,传递给onCreate的匿名函数的第一个参数不是"change“对象。这是一个DocumentSnapshot。onUpdate和onWrite接收“更改”对象,这是另一回事。

票数 3
EN

Stack Overflow用户

发布于 2018-05-14 17:49:26

最后,我花了两天多的时间才弄明白:

第一个问题的答案是change.after.ref.parent;

云修复的云函数示例非常少。

所有的例子都是火基实时数据库。

代码语言:javascript
复制
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});
        });
    });


});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50322373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档