How to import CSV or JSON to firebase cloud firestore

前端 未结 11 1044
星月不相逢
星月不相逢 2020-11-29 16:19

Is there a way to import CSV or JSON to firebase cloud firestore like in firebase realtime database?

11条回答
  •  时光取名叫无心
    2020-11-29 17:05

    You need a custom script to do that.

    I wrote one based on the Firebase admin SDK, as long as firebase library does not allow you to import nested arrays of data.

    const admin = require('./node_modules/firebase-admin');
    const serviceAccount = require("./service-key.json");
    
    const data = require("./data.json");
    
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: "https://YOUR_DB.firebaseio.com"
    });
    
    data && Object.keys(data).forEach(key => {
        const nestedContent = data[key];
    
        if (typeof nestedContent === "object") {
            Object.keys(nestedContent).forEach(docTitle => {
                admin.firestore()
                    .collection(key)
                    .doc(docTitle)
                    .set(nestedContent[docTitle])
                    .then((res) => {
                        console.log("Document successfully written!");
                    })
                    .catch((error) => {
                        console.error("Error writing document: ", error);
                    });
            });
        }
    });
    

    Update: I wrote an article on this topic - Filling Firestore with data

提交回复
热议问题