对 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/