CRUD with Firestore using the Node.js SDK

Kavit (zenwraight)
3 min readApr 24, 2022

--

Cloud Firestore is great for building internal apps because it handles all the complicated ins and outs of managing a database for you. In this tutorial, we’ll show you how to set up a basic CRUD app with the Cloud Firestore using the Node.js SDK:

  • Set up the Cloud Firestore Node.js SDK
  • Create data
  • Read data
  • Update data
  • Delete data

Anyone who likes to follow along with the video, can directly click on the link below and follow along.

Setting up the Node.js SDK for Cloud Firestore

To get started, you’ll first need install the Node.js client library and initialize your instance of the database. You can install the library via npm with:

npm install firebase-admin --save

Once the package is installed, you need to initialize the database. You can do this with Firebase Cloud Functions, the Google Cloud Platform, or through your own server. For this tutorial, we’re going to quickly show you how to initialize the database on your own server using a service account, which is an account identity used to make API requests to an application (learn more about service accounts here).

First, you’ll need to go to the Service Accounts menu in Google Cloud Platform account (it’s under IAM & Admin). From there, generate a new private key, save it as a JSON file, and add it to your server.

Then, in your index.js file, include the firebase-admin library and import your service account private key from your server. Use the firebase-admin library to initialize your application, passing an object with credential as the key and firestore.credential.cert() (with your service account as an argument) as the value.

const fs = require('firebase-admin');const serviceAccount = require('./path/to/key.json');fs.initializeApp({
credential: fs.credential.cert(serviceAccount)
});

Finally, call the firestore() amethod to create your database.

const db = fs.firestore();

Creating data with set()

To fill our database, we’re going to use the set() method. First, we’re going to specify that we want to fill the users collection with the collection() method. To do this, simply pass the name of the collection into the method as a string:

const usersDb = db.collection('users');

Now, we need to specify the first document so we can add our new user. To do this, we’ll use the doc() method. To use this method, pass the id of the document into doc() as a string. For this example, the id is email of the user.

app.post('/create', async (req, res) => {
try {
console.log(req.body);
const id = req.body.email;
const userJson = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName
};
const usersDb = db.collection('users');
const response = await usersDb.doc(id).set(userJson);
res.send(response);
} catch(error) {
res.send(error);
}
});

Reading data with get()

To read your data from Firestore, use the get() method. To read from a collection, specify a collection() before calling get(). Or, if you need to read from a document, specify a doc() before calling get().

app.get('/read/:id', async (req, res) => {
try {
const userRef = db.collection("users").doc(req.params.id);
const response = await userRef.get();
res.send(response.data());
} catch(error) {
res.send(error);
}
});

Updating data with update()

To use the update() method to update a field in a document, pass an object with the field you wish to update as an argument to update().

app.post('/update', async(req, res) => {
try {
const id=req.body.id;
const newFirstName = "hello world!";
const userRef = await db.collection("users").doc(id)
.update({
firstName: newFirstName
});
res.send(userRef);
} catch(error) {
res.send(error);
}
});

Deleting data with delete()

This shouldn’t be a surprise: you delete data from Firestore using the delete() method. It’ll look something like this:

app.delete('/delete/:id', async (req, res) => {
try {
const response = await db.collection("users").doc(req.params.id).delete();
res.send(response);
} catch(error) {
res.send(error);
}
})

Conclusion

Congratulations! You’re now a Cloud Firestore CRUD expert.

I hope this article was useful. If you have any suggestions or complaints, I’ll be glad to find out about it in the comment section.

Stay Safe and Happy Coding.

--

--

Kavit (zenwraight)
Kavit (zenwraight)

No responses yet