我正在尝试将具有downloadUrl的数组从Firebase存储推送到我的Firestore文档中。当我使用下面的代码时,我在Firestore中仅得到一个空数组(矩阵)对象,请参见附件中的图像。
Empty Firestore array (matrix) object.
我当前的代码(在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"
}
}
答案 0 :(得分:0)
不知道为什么我一直问问题,因为我总是最终不得不自己回答。但是对于遇到同样问题的任何人,我都使用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);
});
我希望它会有所帮助。