我正在嘗試撰寫一個云函式,讓我創建一個包含檔案的集合,然后向該檔案添加欄位。目前我的函式會創建集合和評論,但每次都會替換每個欄位并覆寫現有的欄位,因此在推送所有資料后,我只會得到一個欄位。我如何每次添加一個欄位?我的代碼
if (data && typeof data === "object") {
Object.keys(data).forEach((docKey) => {
firestore
.collection(collectionKey)
.doc("quotes")
.set(data[docKey])
.then((res) => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
//});
}
資料
"2": {
"Quote": "Lorem Ipsum"
},
"3": {
"Quote": "123"
},
"4": {
"Quote": "456"
}
在我運行該函式后,檔案引號中的唯一內容是最后一個條目“456”。我如何處理所有停留的領域?
uj5u.com熱心網友回復:
您似乎正在嘗試更新檔案,但您正在使用使用.set()新提供的資料更新檔案的功能。您將需要.update()保留以前的資料。
if (data && typeof data === "object") {
Object.keys(data).forEach((docKey) => {
firestore
.collection(collectionKey)
.doc("quotes")
.update(data[docKey])
.then((res) => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
//});
}
uj5u.com熱心網友回復:
要將欄位添加到現有檔案,請update按照 Anuj 的回答所示使用。
如果您想同時創建初始檔案并使用單個陳述句更新它,您可以將merge: true選項傳遞給set():
firestore
.collection(collectionKey)
.doc("quotes")
.set({ [docKey]: data[docKey] }, { merge: true })
您會注意到我還添加[docKey]: 到資料中,因為我希望您希望 的值docKey成為欄位名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/365562.html
