Javascript Firestore事务:将第一个文档的id设置为第二个文档
我正在尝试将两个文档添加到两个不同的集合中 说coll1和coll2 我将一个文档添加到coll1=>我得到一个文档id,我想将它设置为coll2文档的id,我可以简单地写两个add,但我试图在一个事务中完成它们,因此如果一个失败,两个都会失败Javascript Firestore事务:将第一个文档的id设置为第二个文档,javascript,google-cloud-firestore,transactions,Javascript,Google Cloud Firestore,Transactions,我正在尝试将两个文档添加到两个不同的集合中 说coll1和coll2 我将一个文档添加到coll1=>我得到一个文档id,我想将它设置为coll2文档的id,我可以简单地写两个add,但我试图在一个事务中完成它们,因此如果一个失败,两个都会失败 我不能用电脑完成那件事 下面是我编写的代码,需要转换为Transactions/batched: await db.runTransaction( async function (transaction) { const co
我不能用电脑完成那件事 下面是我编写的代码,需要转换为Transactions/batched:
await db.runTransaction(
async function (transaction) {
const coll1 = {
text: 'This is collection 1 text',
}
const coll1Doc = await db
.collection('coll1')
.add(coll1)
// I tried transaction.set(db.collection('coll1').doc(), coll1) but this doesn't return the doc or the docId which we need in the next step.
// Similay batch.set is also not returning the newly added/edited doc or its Id.
if (coll1Doc && coll1Doc.id) {
const coll1Id = coll1Doc.id
const coll2 = {
text: 'This is collection 2 text',
}
await db
.collection('coll2')
.doc(coll1Id)
.set(coll2)
}
}
)
Firestore文档ID在应用程序代码中生成,并且在统计上保证是唯一的。因此,您的
add()
调用实际上需要执行以下两个步骤:
DocumentReference
DocumentReference
DocumentReference
const coll1Doc = db
.collection('coll1')
.doc();
const id1 = coll1Doc.id;
await coll1Doc.set(coll1);
现在,您可以在第二次写入操作中使用
id1
。“我无法使用此链接完成此操作”->请编辑您的问题以显示您尝试的内容。添加了我的代码和注释。doc.id是什么??我也能做到这一点。。。但我希望在交易或批量中完成此操作。。。因此,如果出现任何问题,它将被还原doc.id
是个打字错误,我现在更新了。您也可以在事务操作中使用此id1
。