How to Import CSV Data into Cloud Firestore

Sample code

Your directory layout will be like this.
・CSV file
・Database Secret JSON file


const firebaseAdmin = require('firebase-admin')
const databaseSecrets = require('./DATABASESECRETS')

  credential: firebaseAdmin.credential.cert(databaseSecrets),
  databaseURL: "DATABASEURL"

const db = firebaseAdmin.firestore()
const fs = require('fs')
const csvSync = require('csv-parse/lib/sync')
const file = 'CSVDATAFILE'
let data = fs.readFileSync(file)
let responses = csvSync(data)

// convert CSV data into objects
let objects = []

responses.forEach(function(response) {
    field0: response[0]
    field1: response[1]
    field2: response[2]
}, this)

// set the data from objects
return db.runTransaction(function(transaction) {
  return transaction.get(db.collection('COLLECTIONNAME')).then(doc => {
    objects.forEach(function(object) {
      transaction.set(db.collection('COLLECTIONNAME').doc(), object)
    }, this)
}).then(function() {
}).catch(function(error) {
  console.log('Failed', error)

What is transaction

Transaction is a set of read and write operations on one or more documents. In a set of atomic operations, either all of the operations succeed, or none of them are applied. You can write up to 500 documents in each transaction.

What is Database Secrets?

It is a key to enter database. You MUST NOT make it public. Once you do that, anyone can enter the database.

How can I get Database Secrets?

  1. Go to your Firebase Console
  2. Click the gear icon on the left side
  3. Click on the Project Settings
  4. Click on the Service Accounts tab
  5. Click on Database Secrets on the bottom
  6. You will get a JSON file

2 thoughts on “How to Import CSV Data into Cloud Firestore”

Leave a Comment