云函数
const newData = value.data();//<<字段修改
吗?
代码:
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};
});发布于 2022-01-16 04:30:51
首先,很好地知道每个文档都是不可变的,在变量中获得一个文档之后,您可以修改该变量,然后需要将/更新/修补新文档。
我的意思是您需要执行2个API调用,以便正确地将文档保存在数据库中。
发布于 2022-01-16 04:54:51
您不能在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()混为一谈,因为您很容易像以前那样陷入困境。在这里,只需使用承诺就可以使代码尽可能简单
https://stackoverflow.com/questions/70727164
复制相似问题