【问题标题】:It is possible to copy firebase document and all it sub collection to another document using angular可以使用 Angular 将 firebase 文档及其所有子集合复制到另一个文档
【发布时间】:2021-03-23 21:13:26
【问题描述】:

大家好, 正如我们从图片中看到的一个示例,我想复制包含在 collection('planaprendizaje') 中的所有文档(及其数据)。

例如,从文档 1 中获取数据并放入文档 10。选择我想要的是 planaprendizaje 还是其他子集合。

我正在使用 Angular 连接到 Firebase 以尝试获取数据。

【问题讨论】:

  • 这绝对是可能的,但没有一个 API 调用可以做到这一点,所以你必须为它编写代码。

标签: angular firebase google-cloud-firestore


【解决方案1】:

这是我的解决方案,但使用了可调用的云函数。您可以使用 source 和 dest 参数。

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 ( data, 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( 'path_to/origin_doc', 'path_to/destination_doc' )
      return { result: 'path_to/destination_doc'  }
    } catch ( e ) {
      throw new functions.https.HttpsError( 'aborted', e.message );
    }
  } );

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 2020-01-22
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多