【问题标题】:Populate the cloud firestore document containing an array of document references填充包含文档引用数组的 Cloud Firestore 文档
【发布时间】:2018-12-07 08:28:04
【问题描述】:

我有一个名为 campgrounds 的集合,其中每个文档都包含一个对 cme​​ts 集合中文档的文档引用数组。 看起来像这样Campground

我正在尝试找出一种方法来填充此 cmets 数组,然后再将其发送到我的 ejs 模板。

我的代码是这样的

app.get("/campgrounds/:docId", function(req, res) {
    var docRef = firestore.collection("campgrounds").doc(req.params.docId);

    try {
        docRef.get().then(doc => {
            if (!doc.exists) {
                res.send("no such document");
            } else {
                // res.send(doc.data());
                res.render("campground", {
                    doc: doc.data(),
                    title: doc.data().title,
                    id: req.params.docId
                });
            }
        });
    } catch (error) {
        res.send(error);
    }
});

【问题讨论】:

  • 不确定这是您要查找的内容,但只需使用doc.data().comments,您将获得一个 cmets Refs 数组。
  • 如何使用文档引用填充 cmets 以便它们可以显示在模板上?

标签: firebase express google-cloud-firestore


【解决方案1】:

在您的数组中存储DocumentReferences。如果您想获取相应文档的数据以便将该数据包含在您的对象中,您应该使用Promise.all() 执行get() 异步操作的变量号(1 个或多个)。

以下应该可以工作(但是根本没有经过测试):

app.get("/campgrounds/:docId", function(req, res) {
var docRef = firestore.collection("campgrounds").doc(req.params.docId);

try {
    var campground = {};
    docRef.get()
    .then(doc => {
        if (!doc.exists) {
            res.send("no such document");
        } else {
            campground = {
                doc: doc.data(),
                title: doc.data().title,
                id: req.params.docId
            };
            var promises = [];
            doc.data().comments.forEach((element, index) => {
                promises.push(firestore.doc(element).get());
            });
            return Promise.all(promises);
        }
    })
    .then(results => {
            var comments = {};
            results.forEach((element, index) => {
                comments[index] = element.data().title  //Let's imagine a comment has a title property
            });
            campground.comments = comments;
            res.render("campground", campground);
    })

} catch (error) {
    res.send(error);
   }
});

请注意,使用此代码您正在执行 1 + N 个查询(N 是 comments 数组的长度)。您可以对您的数据进行非规范化并直接将comments 的数据存储在campground 文档中:然后您只需要一个查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2018-07-01
    • 2022-01-22
    • 2020-07-02
    • 2019-01-08
    相关资源
    最近更新 更多