【问题标题】:How to add a new Firestore document with a nested collection in React?如何在 React 中添加带有嵌套集合的新 Firestore 文档?
【发布时间】:2020-10-29 13:57:15
【问题描述】:

如何在 Firebase/Cloud Firestore 中添加一个带有嵌套集合的新文档?

const createDocument = () => {
        const documentName = prompt('Enter document name:');
        if (documentName) {
            db.collection('despacito').add({
                name: documentName,
            })
}

有什么建议吗?感谢您的宝贵时间。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore nosql


    【解决方案1】:

    根据data model doc,集合和文档是在 Cloud Firestore 中隐式创建的。只需将数据分配给集合中的文档。如果集合或文档不存在,Cloud Firestore 会创建它。

    因此无需实际创建包含嵌套集合的文档。

    根据subcollections documentation 引用子集合中的新文档,您可以将其引用为:

    const messageRef = db.collection('rooms').doc('roomA').collection('messages').doc('message1');
    

    当您使用 .add method 时,它应该类似于:

    db.collection('despacito').doc('documentName').collection('subcollectionname').add({
                    name: nesteddocumentName,
                })
    

    【讨论】:

    • 非常有帮助。谢谢。
    • 没问题,请随时投票/接受答案,以供未来有相同问题的用户参考
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多