首页 > 解决方案 > 如何使用 firebase 函数从 firestore 检索文档并从另一个 firestore 文档添加新数据?

问题描述

我是firebase云功能的新手,在firebase函数中从firestore文档中获取()和设置()数据时遇到了一些麻烦。

这是我在firebase函数中尝试做的事情:

  1. 在firestore中创建新文档“doc1”时访问其数据;
  2. 访问与“doc1”的“用户”字段关联的值;
  3. 该值属于“reference”类型,即指向另一个 Firestore 集合“col2/doc2”中的另一个文档的路径
  4. 使用此路径访问第二个文档“doc2”并检索属于该第二个文档的两个新值以将其添加到第一个文档“doc1”;
  5. 最终目标是将属于“doc2”的“name”和“city”字段的值添加到“doc1”;

到目前为止,我在这里尝试过,我确信我在语法和then()链的使用方面几乎没有问题,但主要思想是:

exports.addDataFromDoc2ToDoc1 = functions.firestore
  .document('col1/{doc1Id}')
  .onCreate((change, context) => {
    const doc1Id = context.params.doc1Id
    const doc1 = change.data()
    const refToDoc2 = doc1.refField

    const doc2Data = refToDoc2.get()
      .then(function (documentSnapshot) {
        if (documentSnapshot.exists) {
          doc2Data = documentSnapshot.data()
          return doc2Data
        }
      })

    const doc1Name = doc2Data.doc1Name
    const doc1City = doc2Data.doc1City

    db.collection('col1')
      .doc(doc1Id)
      .set({
        name: doc1Name,
        city: doc1City
      });
  })

我从 firebase 文档开始: https ://firebase.google.com/docs/functions/firestore-events

const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.writeToFirestore = functions.firestore
  .document('some/doc')
  .onWrite((change, context) => {
    db.doc('some/otherdoc').set({ ... });
  });

如果有人可以帮助我完成这项任务,我将不胜感激,以及如何重组我的算法以提高效率?

非常感谢您的帮助和时间!

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


由于该字段是Reference类型,所以需要使用对象的path属性DocumentReference,如下:

exports.writeToFirestore = functions.firestore
    .document('col1/{doc1Id}')
    .onCreate((snap, context) => {

        const newValue = snap.data();
        const refToDoc2 = newValue.refField;

        return db.doc(refToDoc2.path).get()
            .then((doc) => {
                if (doc.exists) {
                    const name = doc.data().name;
                    const city = doc.data().city;
                    return snap.ref.update({ name, city })
                } else {
                    throw new Error('No document corresponding to the Reference!')
                }
            })
            .catch(error => {
                console.log(error);
                return null;
            });

    });

此外,请注意我们如何链接异步 Firestore 方法返回的承诺,非常重要的是,我们如何返回这个承诺链

另请注意,我们使用的是update()方法,而不是set()一种。


推荐阅读