云功能
- 我想閱讀檔案并編輯一些欄位以將其添加為新檔案。我怎樣才能做到這一點?
常量 newData = value.data(); //<<<欄位修改
- 我可以使用 copyWith 嗎?
代碼:
exports.productCopy = functions.https.onCall( async (data, context)=>{
const uid = context.auth.uid;
data.selectedProductId.forEach((docId){
const productRef = admin.firestore()
.collection('products')
.doc(docId);
const newProductRef = admin.firestore()
.collection('products')
.doc();
const product = await productRef.get().then((value)=>{
const newData = value.data();
newProductRef.add(value.data())
});
});
return {status:'success', isError: false};
});
uj5u.com熱心網友回復:
首先,很高興知道每個檔案都是不可變的,在變數中獲取檔案后,您可以修改該變數,然后您需要放置/更新/修補新檔案。
我的意思是您需要進行 2 次 API 呼叫,才能將檔案正確保存在資料庫中。
uj5u.com熱心網友回復:
你不能真正await在forEach塊中使用。如果要等待多個操作,請使用Promise.all().
它應該是這樣的:
exports.productCopy = functions.https.onCall((data, context) => {
const uid = context.auth.uid;
const promises = data.selectedProductId.map((docId) => {
return admin.firestore() // ?? Return promise, which bubbles up
.collection('products')
.doc() // ?? You need to specify a document ID here, uid maybe?
.get()
.then((doc) => {
const newData = doc.data();
return admin.firestore() // ?? Return promise, which bubbles up
.collection('products')
.doc(docId)
.add(value.data());
});
});
return Promise.all(promises).then((results) => { // ?? Wait for all promises to resolve
return { status:'success', isError: false };
})
});
一般來說,最好不要將async/await與混合then(),因為它很容易陷入你所遇到的情況。在這里,僅使用 Promise 使代碼盡可能簡單
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/412211.html
標籤:
