【问题标题】:How do I create a collection in firebase if it does not exist and add a document to it? [duplicate]如果它不存在,我如何在firebase中创建一个集合并向其中添加一个文档? [复制]
【发布时间】:2020-09-24 21:29:41
【问题描述】:

我在 firebase 中有一个“Houses”集合,它应该包含文档。所以我的函数获取文档数据并将其添加到给定的集合名称中。

如果集合“Houses”不存在,我如何以编程方式创建一个新集合并向其中添加数据? (某种方法来检查集合是否已经存在,如果返回 false 则创建一个新集合?)

这是我的 addData 函数:

exports.addData = functions.https.onCall((data, context) => {

    let validated = true;

    validateForm(data);

    if (validated === false) {
        console.log('Data cannot be validated. Misses the correct attributes')
    } else {
        addAttributes(data);
        for (let i=0; i<data.length; i++) {
                db.collection('Houses')
                .add(data[i])
                .then((docRef) => {
                    console.log('Success ', docRef.id); 
                    return { message: "Done" }
                })
                .catch(err => {
                    console.log('Error logged', err);
                })
        }
    }
})

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    Firestore 集合是用于组织数据的逻辑实体,而不是明确需要创建的东西。如果您将数据添加到集合中,它会被隐式创建——您无需执行任何操作!

    // "Houses" collection doesn't exist
    await db.collection('Houses').add(data);
    // now it does!
    

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2021-04-04
      • 2021-08-19
      • 1970-01-01
      • 2021-04-04
      • 2021-10-30
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多