How to Create Firestore Database by Node.js

2022/10/014 min read
bookmark this
Responsive image

Table of Contents

  1. About Firestore
  2. GCP Account
  3. Create a New Project at Firebase
  4. Create a Collection, Document, and Field at Cloud Firestore Console
  5. Create Service Account Key
  6. Create Node.js to Initialize with Firestore
  7. Add Document to Firestore via Node.js
  8. Get Document from Firestore via Node.js
  9. Conclusion

About Firestore

Firestore is one of Firebase's products. It provides a NoSQL document database that lets users store and query data from mobile or web apps at global scale. This blog will demonstrate how to get started with Firestore using Node.js.

GCP Account

First, you'll need a GCP account. Once you have one, you should be able to click "Go to console" below and get into the Firebase portal. access to Firebase account

Create a New Project at Firebase

Once you're in Firebase, follow the navigation and go to the Firestore section. You will also need to create a new project. All Products > Cloud Firestore

Create a Collection, Document, and Field at Cloud Firestore Console

Here, we start to design our Firestore schema. We'll need to create a collection. In the example below, I created a data structure for testing. As you can see, I have a project called test-project, and my first collection name is my_collection. design firestore schema

Create Service Account Key

The Node.js sample code below accesses Firestore from the local environment to Cloud Firestore. To do that, we'll need to create a service account with access to Firestore.

  • Create a new service account in the Google IAM & Admin section
  • Go to IAM and add the Cloud Datastore Owner role to the service account (you can use a more specific role, but we use this here for simplicity)
  • Go to the Service Accounts section, find the service account, and create a new key
  • Download the JSON key. Once you download the file, you should see that the JSON file has fields such as type, project_id, and private_key_id

Once you have the file, we can start communicating with Firestore from our local environment.

Create Node.js to Initialize with Firestore

Now we'll start coding to make this work. First, set up npm if you don't have it already. This command will create a package.json file:

npm init -y

Then we'll install the following npm package to interact with Firestore. firebase-admin is the official Firebase SDK package that can interact with Firebase, including Firestore. Based on their documentation, the Node.js language seems to support almost all the features Firebase provides. more info about Firebase admin docs

npm install --save firebase-admin

Now create index.js in the correct directory alongside package.json:

const { initializeApp, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');

const serviceAccount = require('./{location to your service account JSON file');

initializeApp({
  credential: cert(serviceAccount),
});

const db = getFirestore();

Add Document to Firestore via Node.js

At this point, you should be able to connect to your Firestore. Now let's try adding some data to our collection.

The code below will connect to the collection, create a new random document, and set the value, or update the existing document if it already exists.

function addData() {
    var randomValue = Math.floor(Math.random() * 100).toString();

    const snapshot = db
      .collection('my_collection')
      .doc(randomValue)
      .set({
        id: "test_" + randomValue,
        list: [6,7,9]
      });
}

addData();

collection result

Get Document from Firestore via Node.js

The sample code below will get all the items from the Firestore collection, and you can loop through the list to find each document.

async function getData() {
    const list = await db.collection('my_collection').get();
    list.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
}
getData();

Also, this code snippet filters by the document ID. It will get all the fields for the document with ID 400. If the document ID does not exist, it will return null.

async function getData() {
  const snapshot = await db.collection('my_collection')
  .doc('400')
  .get();

  console.info('data', snapshot.data());
}
getData();

What if you want to filter by one of the field array list values that contains a particular value? The code below will return any document whose list field contains the value 1.

async function getData() {
  const snapshot = await db.collection('my_collection')
  .where('list', 'array-contains', '1')
  .get();

  snapshot.forEach(doc => {
    console.log(doc.id, '=>', doc.data());
  });

}
getData();

How about filtering with other fields? The following will filter by id and return the matching result:

async function getData() {
  const snapshot = await db.collection('my_collection')
  .where('id', '==', 'test_40')
  .get();

  snapshot.forEach(doc => {
    console.log(doc.id, '=>', doc.data());
  });

}
getData();

Conclusion

This blog covered how to set up Firestore and how to use Node.js to interact with Firestore using different operations.