Firebase云功能在事务中创建文档并使用它来更新另一个文档

时间:2019-04-25 10:55:03

标签: javascript firebase google-cloud-firestore google-cloud-functions

我有一个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 



        }
})

1 个答案:

答案 0 :(得分:1)

以下应该可以解决问题:

  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, {});
      });
  });
相关问题