大家好, 正如我们从图片中看到的示例,我想复制集合('planaprendizaje')中包含的所有文档(及其数据)。
例如,从文档 1 中获取数据并放入文档 10。选择我是否想要 planaprendizaje 或其他子集合。
我正在使用 Angular 连接到 Firebase 以尝试获取数据。
这是我的解决方案,但使用可调用的云函数。您可以使用源参数和目标参数。
const functions = require( 'firebase-functions' );
const admin = require( 'firebase-admin' );
const copyDoc = async ( source, dest ) => {
const docRef = admin.firestore().doc( source );
const docData = await docRef
.get()
.then( ( doc ) => doc.exists && doc.data() )
.catch( ( error ) => {
console.error( 'Error reading document', `${source}`, error.message );
throw new functions.https.HttpsError( 'not-found', 'Copying document was not read' );
} );
if ( docData ) {
await admin
.firestore()
.doc( dest )
.set( docData )
.catch( ( error ) => {
console.error( 'Error creating document', `${dest}`, error.message );
throw new functions.https.HttpsError(
'data-loss',
'Data was not copied properly to the target collection, please try again.',
);
} );
}
const subcollections = await docRef.listCollections();
for await ( const subcollectionRef of subcollections ) {
const subPath = `${source}/${subcollectionRef.id}`
console.log( 'parsing: ', subPath )
try {
const snapshot = await subcollectionRef.get()
const docs = snapshot.docs;
for await ( const doc of docs ) {
console.log( `coping: ${subPath}/${doc.id} -> ${dest}/${subcollectionRef.id}/${doc.id}` )
await copyDoc( `${subPath}/${doc.id}`, `${dest}/${subcollectionRef.id}/${doc.id}` );
}
} catch ( e ) {
throw new functions.https.HttpsError(
'data-loss',
`${e.message} -> ${subPath}, please try again.`,
)
}
}
}
exports.set = functions
.region( 'europe-west3' )
.https.onCall( async ( {source_doc, destination_doc}, context ) => {
if ( !context.auth ) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError( 'unauthenticated', 'The function must be called while authenticated.' );
}
try {
await copyDoc( source_doc, destination_doc )
return { result: destination_doc }
} catch ( e ) {
throw new functions.https.HttpsError( 'aborted', e.message );
}
} );
这仅复制顶级文档及其子集合。如何使其达到任意深度?