Firebase云功能在事务中创建文档并使用它来更新另一个文档
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Firebase云功能在事务中创建文档并使用它来更新另一个文档相关的知识,希望对你有一定的参考价值。
我有一个firebase云功能,它创建一个创建文档的事务,我希望在同一个事务中获取文档的id并更新另一个文档,并引用该文档。
return db.runTransaction(t => {
return t.get(userDocRef)
.then(userDoc => {
var userDocData = userDoc.data();
let ref = db.collection('colect').doc();
return t.set(ref, {'userinfo' : userDocData.name});
}
.then(resp => {
// here `$resp` is reference to transaction and not to the resulted document
// here i want a reference to the new document or the id
// of the document or a way of knowing which document was inserted
}
})
答案
以下应该做的伎俩:
const userDocRef = .....;
let colectDocRef;
return db.runTransaction(t => {
return t
.get(userDocRef)
.then(userDoc => {
const userDocData = userDoc.data();
colectDocRef = db.collection('colect').doc();
return t.set(colectDocRef, { userinfo: userDocData.name });
})
.then(t => {
//I don't know what you exactly want to do with the reference of the new doc, i.e. colectDocRef
//So I just write a new doc in a collection to show that it works
//Just change accordingly to your requirements
const tempoRef = db.collection('colect1').doc();
return t.set(tempoRef, { colectRef: colectDocRef });
})
.then(t => {
//This "fake" update is mandatory unless you'll get the following error: "Every document read in a transaction must also be written."
return t.update(userDocRef, {});
});
});
以上是关于Firebase云功能在事务中创建文档并使用它来更新另一个文档的主要内容,如果未能解决你的问题,请参考以下文章
无法在 razorpay [firebase_functions/internal] 内部的 firebase 云函数中创建订单 ID
在Firestore中创建对Cloud Storage文档的引用