Firebase - Cloud Functions - 对集合进行查询 [英] Firebase - Cloud Functions - make queries on collection

查看:23
本文介绍了Firebase - Cloud Functions - 对集合进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个包含用户和故事的顶级集合.现在,每次来自用户的文档得到更新(仅值 usernamephotoUrl),我想更新故事集合中文档的这些属性.

Lets say I have two top level collection with users and stories. Now everytime a document from user gets update (only the values username or photoUrl), I want to update these properties on a document from the story collection.

一个用户文档可能如下所示(缩短):

One users doc could look like this (shortened):

{
    username: 'blubber',
    photoUrl: 'my/photo/path',
    uid: 'usersUniqueId'
}

故事文档可能如下所示(缩短):

The story doc could look like this (shortened):

{
    username: 'blubber',
    photoUrl: 'my/photo/path',
    uid: 'usersUniqueId',
    sid: 'storiesUniqueId,
    content: '...'
}

现在是云功能部分.我现在不知道如何从包含用户 ID 的故事集合中查询所有文档.现在的代码如下所示:

Now on the cloud functions part. I dont now how to query all documents from the stories collection that contains the users id. The code from now looks like this:

export const onUpdateUser = functions.firestore.document('/users/{userId}')
    .onUpdate((change, context) => {
    const before = change.before.data();
    const after = change.after.data();

    if(before.username !== after.username || before.photoURL !== after.photoURL) {
        return admin.firestore().collection('/stories/')
               .where(before.uid, '==', ***fetch the comparison***)
        // do something
    } else {
        return null;
    }
});

谁能帮我解决这个问题?

Can anyone help me out on this?

推荐答案

更新了下面的代码.几乎拥有它.我添加了异步等待,因为它会使代码更清晰,你会想要添加错误处理等.

Updated the code below. Pretty much had it. I added async await as it will make the code cleaner to follow, you would want to add in error handling etc.

export const onUpdateUser = functions.firestore.document('/users/{userId}')
    .onUpdate(async (change, context) => {
    const before = change.before.data();
    const after = change.after.data();

    if (before.username !== after.username || before.photoURL !== after.photoURL) {
        return admin.firestore().collection('/stories/')
           .where('uid', '==', before.uid).get().then(  
               result => {
                   if (result.size > 0) {
                       result.forEach(async doc => {
                           await doc.ref.update({
                               username: after.username,
                               photoUrl: after.photoUrl
                           })
                        })
                   }
                   return;
               }
           )
    } else {
        return null;
    }
});

这篇关于Firebase - Cloud Functions - 对集合进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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