尝试使用Angular Firebase创建docReference

我想做的是在Firebase数据库中创建一个文档引用,该文档引用会返回一个ID和一个文档引用,因此我可以使用该ID在存储中为该对象的图像创建路径。

因此,根据firebase docs,我应该能够做到这一点:

var newPlantRef = db.collection(`users/${this.userId}/plants`).doc();

但这将返回此错误:

AddPlantComponent.html:30 ERROR FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string,but it was: undefined

所以我在Github上找到了一种解决方法,说我应该这样做:

const id = this.afs.createId();
const ref = this.afs.collection(`users/${this.userId}/plants`).doc(id);

但是当我这样做时:

this.newPlantId = this.db.createId();
this.newPlantRef = this.db.collection(`users/${this.userId}/plants`).doc(this.newPlantId).ref;
this.newPlantRef.update({
      name: 'Test1',primaryImgURL: 'test1',addedDate: new Date()
    });
  }

我收到此错误:

ERROR Error: Uncaught (in promise): FirebaseError: [code=not-found]: No document to update: projects/plant-app-d9298/databases/(default)/documents/users/UoV0MXMfZGhMgmMJHpiMU41aLZG2/plants/LWmM79JotgDn20hPOcA1
FirebaseError: No document to update: projects/plant-app-d9298/databases/(default)/documents/users/UoV0MXMfZGhMgmMJHpiMU41aLZG2/plants/LWmM79JotgDn20hPOcA1

我做错什么了吗?还有其他解决方法,可以在添加之前获取文档ID,以便我的物品和存储可以引用该ID?

jinsong0002 回答:尝试使用Angular Firebase创建docReference

您可以先将文档推送到集合中,然后它将返回文档的ID。在文件路径中使用该ID将其上传到Firestorage,然后可以使用url和路径ref更新文档。

类似的东西

uploadFile(id) {
const file = event.target.files[0];

let filePath = '';
filePath = 'path' + id;

const ref = this.afs.ref(filePath);
const task = ref.put(file);

// observe percentage changes
this.uploadPercent = task.percentageChanges();
// get notified when the download URL is available
return task.snapshotChanges().pipe(
  finalize(() => {
    this.downloadURL = ref.getDownloadURL()
  })
).toPromise();
}


saveData() {
  const collectionRef = this.afs.collection('your path');
  collectionRef.add(data).then((res) => {
  const docId = res.id;
  // then upload the file
  this.uploadFile(docId)
  .then(() => {
              // then update the document
              this.downloadURL.subscribe(imgUrl => {
              const imageUrl = imgUrl;
                // Then update the document with imageUrl using the docId

              });
            });

});

希望有帮助

本文链接:https://www.f2er.com/3162772.html

大家都在问