node.js - Firebase Cloud Functions - 在 Firestore 中移动数据

标签 node.js typescript firebase google-cloud-firestore google-cloud-functions

对 Typescript 语言有非常基本的了解,但想知道如何将多个文档从一个 Firestore 数据库集合复制到另一个集合?

我知道如何从应用代码发送请求以及相关数据(字符串和 firebase 身份验证用户 ID),但不确定处理请求的 Typescript 代码...

最佳答案

这是一个非常广泛的问题,但类似这样的问题可以将中等大小的数据从一个集合移动到另一个集合:

import * as _ from 'lodash';   
import {firestore} from 'firebase-admin';

export async function moveFromCollection(collectionPath1: string, collectionPath2: string): void {
    try {
        const collectionSnapshot1Ref = firestore.collection(collectionPath1);
        const collectionSnapshot2Ref = firestore.collection(collectionPath2);

        const collectionSnapshot1Snapshot = await collectionSnapshot1Ref.get();
        // Here we get all the snapshots from collection 1. This is ok, if you only need
        // to move moderate amounts of data (since all data will be stored in memory)
        // Now lets use lodash chunk, to insert data in batches of 500
        const chunkedArray = _.chunk(collectionSnapshot1Snapshot.docs, 500);
        // chunkedArray is now an array of arrays, with max 500 in each
        for (const chunk of chunkedArray) {
            const batch  = firestore.batch();
            // Use the batch to insert many firestore docs
            chunk.forEach(doc => {
                // Now you might need some business logic to handle the new address,
                // but maybe something like this is enough
                const newDocRef = collectionSnapshot2Ref.doc(doc.id);
                batch.set(newDocRef, doc.data(), {merge: false});
            });
            await batch.commit();
            // Commit the batch
        }
        console.log('Done!');
    } catch (error) {
        console.log(`something went wrong: ${error.message}`);
    }
}

但是也许您可以详细介绍一下用例?

关于node.js - Firebase Cloud Functions - 在 Firestore 中移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656869/

相关文章:

node.js - HTTPS 与 NodeJS swagger-express-mw npm 包

reactjs - 将 Redux-Form 与 React-Redux connect 结合使用时出现 TypeScript 错误

javascript - Webpack:如何在一个全局变量下隐藏导出函数/变量?

node.js - 如何配置使用从 PureScript 编译的 JavaScript 模块的 TypeScript 项目?

javascript - 用于非异步的 Node JS

node.js - 如何创建可公开访问的文件

javascript - Angular 2 : select not updating with selected value in ion-select Ionic 2?

javascript - 在云函数中获取文档值

javascript - 如何在实时数据库中创建一个id

reactjs - 如何在 onSnapshot() 中使用 orderBy() 以便我可以根据时间戳对文档进行排序?