代码之家  ›  专栏  ›  技术社区  ›  Paco Zevallos

将子集合添加为单个ID文档Firestore的一部分

  •  1
  • Paco Zevallos  · 技术社区  · 6 年前

    我试图将多个图像(以前加载到存储中)的URL保存在firestore文档的子集合中。

    img )每一张图片都不是我想要的:

    enter image description here

    我想要的是在子集合中生成每个文档 img : enter image description here

    我知道这个功能 guardarImagen() 被每个图像迭代,但我不知道如何将其分离,以便它在第一级生成单个文档(在第二级,它将是子集合,在那里,如果迭代,它是好的),我不知道我是否让自己被理解。

    import { Injectable } from '@angular/core';
    
    import { AngularFirestore } from 'angularfire2/firestore';
    import * as firebase from 'firebase/app';
    import { FileItem } from '../class/file-item';
    
    @Injectable({
      providedIn: 'root'
    })
    export class CargaImagenesService {
    
      private myFolder = 'img';
    
      constructor(private db: AngularFirestore) { }
    
      cargarImagenesFirebase(imagenes: FileItem[]) {
    
        const myTest = this.db.collection('test').ref.doc();
        console.log(myTest.id)
    
    
        const storageRef = firebase.storage().ref();
    
        for (const item of imagenes) {
          item.estaSubiendo = true;
          if (item.progreso >= 100) {
            continue;
          }
    
          const uploadTask: firebase.storage.UploadTask =
            storageRef.child(`${this.myFolder}/${item.nombreArchivo}`)
              .put(item.archivo);
    
          uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
            (snapshot: firebase.storage.UploadTaskSnapshot) =>
              item.progreso = (snapshot.bytesTransferred / snapshot.totalBytes) * 100,
            (error) => console.error('Error al subir', error),
            () => {
              console.log('Imagen cargada correctamente');
              uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                item.url = downloadURL;
                item.estaSubiendo = false;
                this.guardarImagen({
                  nombre: item.nombreArchivo,
                  url: item.url
                });
              });
            });
        }
    
      }
    
      
      guardarImagen( imagen: { nombre: string, url: string } ) {
        this.db.collection('test2').ref.doc().collection(`/${this.myFolder}`).add(imagen);
         
      }
    
    
    }
    2 回复  |  直到 6 年前
        1
  •  2
  •   Renaud Tarnec    6 年前

    问题很可能来自于 guardarImagen() 功能:

     this.db.collection('test2').ref.doc().collection(`/${this.myFolder}`).add(imagen);
    

    事实上,你是这样做的 doc() :

    如前所述 here 这个 博士() 方法“获取集合中指定路径处文档的DocumentReference。 如果未指定路径,将使用自动生成的唯一ID 用于返回的文档参考。"

    你应该这样做:

    this.db.collection('test2').ref.doc('myDoc1').collection(`/${this.myFolder}`).add(imagen);
    

    i、 e.指定要填充子集合的文档,而不是在每次调用函数时创建一个新文档(通过调用自动生成的唯一ID) 博士() 没有任何路径)

    // 根据Tim Martens的回答和评论进行编辑 ,提到“添加 .ref 将其转换为本机 firebase.firestore.CollectionReference "

        2
  •  1
  •   Tim Martens    6 年前

    根据雷诺回答中的评论:
    const docRef = this.db.collection('test3').doc(); :这里是 .ref 是这样失踪的:
    const docRef = this.db.collection('test3').ref.doc();

    你需要通过这个 documentReference 给你的 guardarImagen() 功能:

    cargarImagenesFirebase() {
    
        const imagenes = [
            { nombre: 1, url: 'https://url1/1.png' },
            { nombre: 2, url: 'https://url2/2.png' },
            { nombre: 3, url: 'https://url3/3.png' }
        ];
    
        const testDocRef = this.db.collection('test').ref.doc();
    
        for (const item of imagenes) {
            this.guardarImagen(testDocRef, item);
        }
    }
    
    guardarImagen(testDocRef: DocumentReference, item: { nombre: number; url: string; }): any {
        testDocRef.collection(this.myFolder).add(item);
    }
    

    为了简单起见,我省略了上传/存储部分。