如何将Firestore子集合数据导出到CSV [英] How to export Firestore subcollection data to CSV

查看:85
本文介绍了如何将Firestore子集合数据导出到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将Firestore集合的子集合导出到CSV文件中.

I'm trying to export subcollection of a firestore collection to a CSV file with the following code.

用于此操作的npm是"json2csv"

The npm used for this is "json2csv"

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const json2csv = require("json2csv").parse;
exports.csvJsonReport = functions.https.onRequest((request, response) => {
    const db = admin.firestore();
    const data = db.collection("collectionname").doc().collection("subcollection") //collection name ,documentid, subcollection
    return data.get().then((querySnapshot) => {
        var object = {}
        var jsondata = [];
        querySnapshot.forEach(doc => {
            object = doc.data();
            object['docid'] = doc.id; // must add this line after doc.data
            console.log("objectbefore", object)
            jsondata.push(object);
            console.log("objectafter", object)
            console.log(jsondata);
        });
        const csv = json2csv(jsondata);
        response.setHeader(
            "Content-disposition",
            "attachment; filename=files.csv"//file name.csv
        );
        response.set("Content-Type", "text/csv");
        return response.status(200).send(csv)
    }).catch((err) => {
        return console.log(err);
    });
});

但是我在输出CSV文件中得到的结果只是没有内部子集合的集合.

But the result that I get in the output CSV file is only the collection without the inner subcollections.

是否可以通过这种方法导出子集合数据?如果没有,如何将子集合数据导出到CSV?

is it possible to export subcollection data in this method? If not, how can I export subcollection data to CSV?

编辑#1:代码已更新.这是我得到的错误 错误:数据不应为空,或应包含字段"选项

edit #1: code is updated. This is the error I get Error: Data should not be empty or the "fields" option should be included

推荐答案

Firestore中的查询很浅,这意味着当您查询collectionname集合时,您会获得该集合中的文档,但是您不要在子集合中获取文档.

Queries in Firestore are shallow, meaning that when you query the collectionname collection you get the documents within this collection but you DON'T get the documents within the subcollections.

您必须一个一个地查询每个子集合,以便获取它们包含的文档并将其内容添加到CSV中.

You'll have to query each sub-collection, one by one, in order to get the documents they contains and add their content to your CSV.

如果您不知道这些子集合的名称(即它们是由用户在使用您的应用程序时创建的,而不是由数据库架构师在设计数据模型时创建的),则可以在以下

In case you don't know the names of those subcollections (i.e. they were created by the users while using your app and not by the database architect while designing the data model) you will find in the following article a method for listing all subcollections of a Firestore document with a Cloud Function (disclaimer, I'm the article author).

这篇关于如何将Firestore子集合数据导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆