Firestore 事务:将第一个文档的 id 设置为第二个文档
Firestore transaction: set id of the first document to the second document
我正在尝试将两个文档添加到两个不同的集合中。
说 coll1 和 coll2。
我将文档添加到 coll1 => 我得到文档 ID,我想将其作为 ID 设置到 coll2 文档,我可以简单地写两个添加,但我试图在事务中完成这些, 因此,如果一个失败,两个都失败。
我无法使用 this link
完成该操作
下面是我的代码,需要转成transations/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()
调用基本上需要执行以下两个步骤:
- 生成新的唯一 ID
- 为该 ID 创建
DocumentReference
- 在
DocumentReference
中设置数据
有了这些知识,您可以根据您在不使用交易对象的情况下获得的 ID 自己构建 DocumentReference
。
const coll1Doc = db
.collection('coll1')
.doc();
const id1 = coll1Doc.id;
await coll1Doc.set(coll1);
现在您可以在第二次写入操作中使用id1
。
我正在尝试将两个文档添加到两个不同的集合中。
说 coll1 和 coll2。
我将文档添加到 coll1 => 我得到文档 ID,我想将其作为 ID 设置到 coll2 文档,我可以简单地写两个添加,但我试图在事务中完成这些, 因此,如果一个失败,两个都失败。
我无法使用 this link
完成该操作下面是我的代码,需要转成transations/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()
调用基本上需要执行以下两个步骤:
- 生成新的唯一 ID
- 为该 ID 创建
DocumentReference
- 在
DocumentReference
中设置数据
有了这些知识,您可以根据您在不使用交易对象的情况下获得的 ID 自己构建 DocumentReference
。
const coll1Doc = db
.collection('coll1')
.doc();
const id1 = coll1Doc.id;
await coll1Doc.set(coll1);
现在您可以在第二次写入操作中使用id1
。