【问题标题】:Save reference to other collection保存对其他集合的引用
【发布时间】:2018-05-05 23:40:40
【问题描述】:

如何在 Firebase Firestore 中保存对另一个集合的引用? docs on adding data 没有提及保存引用的任何内容。

【问题讨论】:

    标签: firebase firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    Firestore 支持存储对文档 (DocumentReference) 的引用而不是对集合的引用,但您可以像任何其他 supported data type 一样将 DocumentReference 添加到数据库中,在 JavaScript 中是这样的:

    db.collection("cities").doc("LA").set({
        name: "Los Angeles",
        state: db.collection("states").doc("CA"),
        country: "USA",
    });
    

    【讨论】:

    • 对于那些寻求澄清的人,您确实需要使用.ref 才能正确存储数据。在这种特定情况下,您需要:state: db.collection('states').doc('CA').ref,
    • @AmitBravo 不,将其视为pointer,因此您需要读取其他文档的值。
    • 是的,我今天晚些时候就知道了,我们可以像 db.collection("cities").doc("LA").get() .then(doc => { if ( doc.exists) { console.log("文档数据:", doc.data().state.get); doc.data().state.get() .then(data2 => { console.log('data2 ',data2.data()) }) } }) .catch(function(error) { console.log("获取文档时出错:", error); });
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 2016-02-01
    • 2018-05-27
    相关资源
    最近更新 更多