How to Create Firestore database by Node.js

2022/10/014 min read
bookmark this

About Firestore

Firestore is one of the Firebase's product, provide NoSQL document database let user to store, query data from mobile or web apps at global scale. This blog will demo and shows how to get start with fireStore with node.js.

GCP Account

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

Create a new project at Firebase

Once get into the Firebase, follow the navigation and go to the Firestore section and will need to create a new project as well. 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, below example for testing I created data structure as this. As you can see, I have a project as test-project, and my first collection name is my_collection. design firestore schema

Create service account key

The below Node.js sample code to access fireStore will from the local environment to cloud fireStore, to do that we'll need to create service account and has access to fireStore.

  • create a new service account at google IAM & Admin section
  • go to the IAM and add Cloud Datastore Owner role to the service account (You should be able to do more specific role here we just use for make it easier.)
  • go to service accounts section and find the service account and create a new key
  • download the json key, once you download the file you should see the JSON file has name as type, project_id, or private_key_id Once have the file, we can start to communicate with fireStore from our local environment now.

Create Node.js to initialize with Firestore

Now, we'll start to do some coding to make this work now, first need to setup a npm if you don't have already. This command will create package.json file.

npm init -y

Then, we'll install the following npm package for interact with fireStore. firebase-admin is fireStore official SDK package can interact with Firebase include the fireStore. Base on their document, seems like Node.js language support almost all the feature firebase provided. more info about FIrebase admin docs

npm install --save firebase-admin

Now, create index.js under correct directory with along with 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, should be able to connect to your fireStore. Now, let's try adding some data to our collection.

Below code, will connect to the collection and create a new random document and set the value, or update the existing document if already exist.

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

Below sample code will get all the list from the fireStore for the collection, and you can loop the list and find each documents.

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 is for filter by the document id, this will get all the filed by the document id 400. If the document id not exist then will return null.

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

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

What about if want to filter one of the field array list contains particular value? Below code will return any field list has contains value as 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 other filter with other field? So this will filter the id and return the match find.

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 setup fireStore, and how to use Node.js to interact with fireStore with different operations.