Вставить массив в существующий документ Firestore - PullRequest
0 голосов
/ 30 июня 2018

Я пытаюсь отправить массив с downloadUrl из хранилища Firebase в мой документ Firestore. Когда я использую приведенный ниже код, я получаю только пустой массив (матрицу) в Firestore, см. Изображение во вложении.

Пустой объект массива (матрицы) Firestore.

Мой текущий код (добавляется после создания документа в Firestore)

this.docRef = docRef.id;
this.houseRef = this.afs.collection('houses').doc(this.docRef);

  if (this.filesToUpload && this.filesToUpload.length) {

    for (var i = 0; i < this.filesToUpload.length; i++) {
      console.log("Adding photo's" + this.filesToUpload[i]);
      const filePath = 'images/' + docRef.id + '/' + i + '.jpg';
      const ref = this.storage.ref(filePath);
      // const task = ref.put(this.imagePaths[i], metadata).then((snapshot) => {
      const task = ref.put(this.filesToUpload[i]).then((snapshot) => {
        // const task = ref.put(imageBlob).then((snapshot) => {
        console.log('Uploaded an image!');


        const downloadUrl = ref.getDownloadURL();
        console.log("downloadURL: " + downloadUrl);
        this.images.push(String(downloadUrl));


      });
    }
    this.imagesArray = this.images.map((obj) => { return Object.assign({}, obj) });
    this.houseRef.update({'images': this.imagesArray});
  }

Я хотел бы добавить массив в моем текущем документе Firestore, который выглядит следующим образом:

images: {
  image0: {
      downloadUrl: "path to firebase storage's downloadUrl"
  }
}

1 Ответ

0 голосов
/ 13 июля 2018

Понятия не имею, почему я продолжаю задавать вопросы, потому что мне всегда приходится отвечать на свои вопросы. Но для тех, у кого такая же проблема, я исправил ее с помощью транзакций Firestore.

Мой текущий код:

this.afs.firestore.runTransaction((t) => {
              return t.get(firebaseRef).then((doc) => {
                // doc doesn't exist; can't update
                if (!doc.data().images2) {
                  console.log("if images2 not found");
                  t.set(firebaseRef, { 'images2': [imageData] }, { merge: true });
                } else {
                  console.log("If images2 found");
                  //const newImagesArray = doc.get('images2').push( {downloadUrl: url} );
                  const existingImages = doc.data().images2;
                  existingImages.push(imageData);
                  t.set(firebaseRef, { images2: existingImages }, { merge: true });
                }
              });
            }).then(function () {
              console.log("Transaction successfully committed!");
            }).catch(function (error) {
              console.log("Transaction failed: ", error);
            });

Надеюсь, это поможет.

...