Облачная функция Firebase создает документ в транзакции и использует его для обновления другого документа - PullRequest
0 голосов
/ 25 апреля 2019

У меня есть облачная функция firebase, которая создает транзакцию, которая создает документ, и я хочу в той же транзакции получить идентификатор документа и обновить другой документ со ссылкой на этот документ.

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 Ответ

1 голос
/ 25 апреля 2019

Следующее должно сделать трюк:

  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, {});
      });
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...